如何定义ManyToManyField以默认只检索不同的对象?

时间:2015-05-27 05:20:02

标签: django

Datetime

在上述情况下,我怎么能以某种方式破解相关经理class UserProfile(Model): base = OneToOneField(User) commented_articles = ManyToManyField('Article', through='Comment') 默认使用commented_articles方法过滤文章?

我知道我可以通过调用distinct()方法来获取不同的文章,如:

distinct()

但我希望相关管理员>>> u = UserProfile.objects.first() >>> u.commented_articles.distinct() 本身默认包含commented_articles查询,而实施则在模型的定义中占据一席之地。

有没有什么好方法可以让相关管理器默认返回明确过滤的查询集?

1 个答案:

答案 0 :(得分:0)

如果您未指定自定义distinct()参数,

through将是多余的;虽然我当然可以理解为什么你这样做。为什么不让commented_articles成为一个返回你真正想要的查询集的缓存属性,例如:

class UserProfile(Model)
    ...
    @cached_property
    def commented_articles(self):
        return Article.objects.filter(comment__userprofile=self).distinct()
如果您需要在ManyToManyFields模型中存储除关系之外的任何内容,那么

through就不那么有用了。无论如何,Django ORM将为您提供关系。

相关问题