在布尔字段上添加时间戳

时间:2011-06-21 00:20:46

标签: django django-models django-views

我有一个视频对象,管理员可以使用它。我希望能够根据这些精选视频的制作日期对这些精选视频进行排序。

以下是我目前的模特 -

class VideoMedia(models.Model):
    uploaded_by = models.ForeignKey('UserProfile')
    video = models.ImageField(upload_to='videos')
    info = models.ForeignKey('VideoInfo', blank = True, null=True)

class VideoInfo(models.Model):
    title = models.CharField(max_length=256)
    featured = models.BooleanField # need time also
    ...

我的相关视图代码如下所示 -

video_set = VideoInfo.objects.all()
    if sort == 'featured':
        videos = video_set.filter(featured=1) # .order_by('timestamp') ?

我尝试在特色字段中添加FK,但这使我在视图/模板中很难显示正确的数据。

class FeaturedVideos(models.Model):
    video = models.ForeignKey(VideoMedia)
    timestamp = models.DateTimeField(auto_now_add=True)
# in view
    if sort == 'featured':
        videos = FeaturedVideos.objects.order_by('timestamp')
        # this doesn't work, because I need to be relative to the VideoInfo model
        # for the information to display correctly in the template

完成此任务最直接的方法是什么?谢谢。

1 个答案:

答案 0 :(得分:1)

过去我使用了一个可空的datetimefield作为布尔值。当它为null时,你知道它是假的,当它有一个日期你知道它是真的,并且该字段被设置为True的日期和时间。

从一个领域获得两种用途是一种便宜而简单的方法。您还可以向模型添加一些简单属性,以便在使用模板时更轻松。这是一个非常简单的例子。

class VideoInfo(models.Model):
    title = models.CharField(max_length=256)
    featured = models.DateTimeField(null=True, blank=True)

    @property
    def is_featured(self):
        if self.featured:
           return True
        else:
           return False