I'm building a Django app that needs to store multiple selected dates for an event. The first thing that came to mind was build the event model:
class Event(models.Model):
title = models.CharField(max_length=200)
c开发者_开发问答reator = models.ForeignKey(User)
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
class Meta:
ordering = ('title',)
Then build a separate table of EventDates:
class EventDate(models.Model):
event = models.ForeignKey(Event)
date = models.DateField()
modified = models.DateTimeField(auto_now=True, auto_now_add=False)
created = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return "%s / %s" % (self.event, self.date)
class Meta:
ordering = ('created',)
But is this the best way? Is there a better performing alternative, like a comma separated string?
The best way is the one that best serves your purposes. There is no built-in comma separated field in Django, but you can easily roll your own one - the problem is if this is what you really need.
For example - if you need to filter events based on their dates, I'm not sure how you could easily do this with such comma separated field, but I can clearly see how you could do this with your current approach:
Event.objects.filter(eventdate_set__date=my_date)
-- so unless you specify your planned usage pattern, I don't think there is a general answer.
精彩评论