Add a timestamp on a boolean field
I have a video object, which an administrator can feature. I want to be able to sort those featured videos by the date they were made featured.
Here are the models I currently have --
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
...
My relevant view code looks like this --
video_set = VideoInfo.objects.all()
if sort == 'featured':
videos = video_set.filter(featured=1) # .order_by('timestamp') ?
I tried adding a FK to the featured field, but it makes it very difficult for me in the view/template to display the correct data.
class FeaturedVideos(models.Model):
video = models.ForeignKey(VideoMedia)
timestamp = models开发者_JS百科.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
What would be the most straightforward way to accomplish this task? Thank you.
In the past I have used a nullable datetimefield as a boolean. When it is null then you know it is false, and when it has a date you know it is true, and the date and time that field was set to True.
It is a cheap and easy way to get two uses out of one field. You can also add some simple properties to your model to make it easier when using templates. Here is a pretty quick example.
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
精彩评论