简体   繁体   English

在OnetoOne模型中按字段过滤查询集

[英]Filter Queryset by field in OnetoOne model

I have a model from a 3rd party app that I can't (really don't want to) modify, so I extended it with OnetoOne field like this: 我有一个来自第三方应用程序的模型,我不能(真的不想)修改它,所以我用OnetoOne字段扩展了它,如下所示:

class Model(models.Model):
    title = models.CharField ....
    content = ....

class ModelExtended(models.Model):
    gallery = models.OneToOneField(Gallery, related_name='galleryextended')
    author = models.Charfield()

So what I want to do is create a view for all authors. 所以我要做的是为所有作者创建一个视图。 I want a queryset that contains no more than one object of each author. 我想要一个查询集,其中每个作者最多包含一个对象。 So if there's 50 Model.objects.all(), but only 2 unique authors entered, only 2 Model objects should be returned. 因此,如果有50个Model.objects.all(),但仅输入了2个唯一作者,则应仅返回2个Model对象。

I've tried: 我试过了:

queryset = Model.objects.order_by('author').distinct()

which returns: Cannot resolve keyword 'author' into field. 返回:无法将关键字“作者”解析为字段。 Choices are: date_added, description, modelextended, id, is_public, photos, sites, slug, tags, title 选项包括:添加日期,描述,扩展模型,id,is_public,照片,网站,子弹,标签,标题

queryset=Model.objects.order_by('modelextended.author').distinct()

which returns the same as Model.objects.all() 返回与Model.objects.all()相同的结果

queryset = ModelExtended.objects.order_by('author').distinct()

which returns no results at all. 这根本不返回任何结果。 I am running Postgresql because I read that it only can use .distinct() 我正在运行Postgresql,因为我读到它只能使用.distinct()

queryset = Model.objects.order_by('modelextended__author').distinct('modelextended__author')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM