如何使用自定义管理器与相关对象?

时间:2011-09-20 18:03:12

标签: django django-managers django-orm

我有一位自定义经理。我想将它用于相关对象。我在文档中找到了use_for_related_fields。但它不像我使用它那样工作:

class RandomQueryset(models.query.QuerySet):

    def randomize(self):       
        count = self.count()
        random_index = random.randint(0, count - 1)
        return self.all()[random_index]


class RandomManager(models.Manager):

    use_for_related_fields = True

    def get_query_set(self):
        return RandomQueryset(self.model, using=self._db)

    def randomize(self):
        return self.get_query_set().randomize()

我将它用于一个型号:

>>> post = PostPages.default_manager.filter(image_gallery__isnull=False).distinct().randomize()

并试图对m2m相关对象做同样的事情:

>>> post.image_gallery.randomize()

出现错误:

AttributeError: 'ManyRelatedManager' object has no attribute 'randomize'

是否可以像我一样使用自定义管理器?如果是这样,你如何使其发挥作用?

修改

我的模特:

class ShivaImage(models.Model, ImageResizing):
    image = models.ImageField(upload_to='img')
    slide_show = models.BooleanField() 
    title = models.CharField(max_length=100)
    text = models.TextField(max_length=400)
    ordering = models.IntegerField(blank=True, null=True)

    objects = RandomManager()


class PostPages(models.Model):
    image_gallery = models.ManyToManyField(ShivaImage, blank=True,
                                       related_name='gallery',)
    # all the other fields... 

    objects = RandomManager()

4 个答案:

答案 0 :(得分:23)

在管理器上将use_for_related_fields设置为True将使其可用于将指向的所有关系,并将此管理器定义为默认管理器。记录在案here

class MyManager(models.Manager):
    use_for_related_fields = True
    # ...

我认为您只在PostPages模型上启用了它,而不是在Gallery模型上(或通过post_image_gallery引用的模型调用)。如果您想在此Realtion Manager上拥有其他功能,则需要向use_for_related_fields = True模型添加Gallery的自定义默认管理器!

答案 1 :(得分:23)

为了完整主题,Django 1.7(最后)支持using a custom reverse manager,所以你可以做类似的事情(只需从django文档中复制):

from django.db import models

class Entry(models.Model):
    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager='entries').all()

答案 2 :(得分:8)

在django 2.0 use_for_related_fields已弃用https://docs.djangoproject.com/en/2.0/releases/1.10/#manager-use-for-related-fields-and-inheritance-changes

您应该使用base_manager_namehttps://docs.djangoproject.com/en/2.0/ref/models/options/#django.db.models.Options.base_manager_name

更新了文档:https://docs.djangoproject.com/en/2.0/topics/db/managers/#using-managers-for-related-object-access

class MyModel(models.Model):
    field1 = ...
    field2 = ...
    special_manager = MyManager()

    class Meta:
        base_manager_name = 'special_manager'

答案 3 :(得分:2)

此外,在自定义管理器中,确保通过self.get_query_set()访问查询集 实现从相关管理器调用的自定义过滤器时的代理方法:

class EventManager(models.Manager):

    use_for_related_fields = True

    def visible_events(self):
        today = datetime.date.today()
        # don't do this !!! 
        # unsuitable for related managers as could retrieve extraneous objects
        # qs = super(EventManager, self).get_query_set()
        # Use queryset proxy method as follows, instead:
        qs = self.get_query_set()
        qs = qs.filter(visible_from__lte=today, visible_to__gte=today)
        return qs


class Event(models.Model):

    visible_from = models.DateField(_(u'visible from'), null=False, blank=False)
    visible_to = models.DateField(_(u'visible to'), null=False, blank=False)
    concepts = models.ManyToManyField(Concept, through='ConceptEventRegistration')

    objects = EventManager()

样本用法:

my_concept = Concept.objects.get(id=1)
# retrieve all events related to the object
my_concept.event_set.all()
# retrieve all visible events related to the object
my_concept.event_set.visible_events()