开发者

What is the best way to store multiple date strings in Django?

开发者 https://www.devze.com 2022-12-20 16:50 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号