开发者

How to always filter on a field on objects requests

I have two models :

class Album(models.Model):
#Attributes
title = models.CharField(max_length=200)
displayed = models.BooleanField()
created_on = models.DateTimeField(auto_now_add=True)

class Photos(models.Model):
#Attributes
title = models.CharField(max_length=500)
link = models.CharField(max_length=500)
album = models.ForeignKey(Album, unique=False, verbose_name=_('album'))

def upload_path(self, filename):
    return 'upload/photos/%s/%s' % (self.id, filename)

def upload_path_thumbnail(self, filename):
    return 'upload/photos/%s/%s' % (self.id, "thumnail_" +filename)

thumbnail = models.I开发者_开发技巧mageField(upload_to=upload_path_thumbnail)                             
photo = models.ImageField(upload_to=upload_path)
created_on = models.DateTimeField(auto_now_add=True)
displayed = models.BooleanField() 

And I want to force, when i select Photos, to always filter on displayed=1.

Thank you


Use a custom manager:

class DisplayedPhotoManager(models.Manager):
    def get_queryset(self):
        return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)

class Photos(models.Model):
    objects =  DisplayedPhotoManager()   
    ...

this will override standard "objects" manager (which can be dangerous).

A nicer pattern is often:

class DisplayedPhotoManager(models.Manager):
    def get_queryset(self):
        return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)

class Photos(models.Model):
    objects = models.Manager()
    displayed = DisplayedPhotoManager()   
    ...

and use 'displayed' instead of 'objects':

Photo.displayed.all()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜