2015-05-27 38 views
1
class UserProfile(Model): 
    base = OneToOneField(User) 
    commented_articles = ManyToManyField('Article', through='Comment') 

在上述情况下,我怎么能以某种方式破解相关经理commented_articles过滤与distinct()法默认的文章?如何定义ManyToManyField以仅默认检索不同的对象?

我知道我可以通过调用distinct()方法一样得到截然不同的文章:

>>> u = UserProfile.objects.first() 
>>> u.commented_articles.distinct() 

但我想相关的经理commented_articles本身含有distinct()查询默认情况下,同时实现取模型的定义的地方。

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

+1

问题是,为什么你甚至连数次存储值?这种行为是否需要?如果是这样,你可以用'use_for_related_fields = True'来编写[qustom manager](https://docs.djangoproject.com/en/1.8/topics/db/managers/#manager-types)。 – sobolevn

+0

'use_for_related_fields'不适用于M2M字段(至少尚未),请参阅[link](https://code.djangoproject.com/ticket/14891)1 – dzejdzej

回答

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将为您提供关系。

相关问题