如何将自定义管理器与相关对象一起使用? [英] How to use custom manager with related objects?

查看:306
本文介绍了如何将自定义管理器与相关对象一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义经理.我想将其用于相关对象.我在文档中找到了 use_for_related_fields .但这并不能像我以前那样使用它:

I have a custom manager. I want to use it for related objects. I found use_for_related_fields in docs. But it does not work the way I used it:

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相关的对象执行相同的操作:

And tried to do the same with m2m related object:

>>> post.image_gallery.randomize()

出现错误:

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

是否可以按照我的方式使用自定义管理器?如果是这样,您如何使它工作?

Is it possible to use a custom manager in the way I did it? If so, how do you make it work?

我的模特:

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()

推荐答案

在管理器上将use_for_related_fields设置为True将使它在指向指向的模型的所有关系中可用将此经理定义为默认经理. 此处

Setting use_for_related_fields to True on the manager will make it available on all relations that point to the model on which you defined this manager as the default manager. This is documented here

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

我想您只在PostPages模型上启用了它,而不在Gallery模型上(或通过post_image_gallery引用的任何称为模型的)模型上启用了它.如果您想在此Realion Manager上具有其他功能,则需要在Gallery模型中添加一个自定义的默认管理器,其中带有use_for_related_fields = True

I suppose you have it only enabled on your PostPages model, not on your Gallery model (or whatever the model is called that is referenced through post_image_gallery). If you want to have additionally functionality on this realtion manager you need to add a custom default manager with use_for_related_fields = True to your Gallery model!

这篇关于如何将自定义管理器与相关对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆