简体   繁体   English

Django - 如何构建 GenericRelation 查询?

[英]Django - how to build a GenericRelation query?

I'm trying to access all my different model objects by the Hit table.我试图通过 Hit 表访问我所有不同的模型对象。 What I do not understand is why I'm unable to Build the actual query to do that.我不明白的是为什么我无法构建实际查询来做到这一点。 I simply want to get all objects at queryset_m1-m3 where the Model1-3.pk is the hit.object_id as hit.object_id is the primary key of a related object of Model1, 2 or 3.我只想获取 queryset_m1-m3 中的所有对象,其中 Model1-3.pk 是 hit.object_id,因为 hit.object_id 是 Model1、2 或 3 的相关对象的主键。

def recently_viewed_proposals():
    hit = Hit.objects.all()
    queryset_m1 = Model1.objects.filter(pk=hit.object_id)
    queryset_m2 = Model2.objects.filter(pk=hit.object_id)
    queryset_m3 = Model3.objects.filter(pk=hit.object_id)
    hit_elements = chain(
        queryset_m1.random(len(queryset_m1)),
        queryset_m2.random(len(queryset_m2)),
        queryset_m3.random(len(queryset_m3))
    )
    elements_list = list(hit_elements)
    n_proposals = min(len(elements_list), config.MAX_RECENTLY_VIEWED_PROPOSALS)
    recently_viewed_proposals = random.sample(elements_list, n_proposals)
    return recently_viewed_proposals

This is how my Hit model Class looks like:这是我的 Hit 模型类的样子:

...

class Hit(models.Model):
    content_type = models.ForeignKey(ContentType, limit_choices_to=hit_models, on_delete=models.CASCADE)
    object_id = models.CharField(max_length=36)
    content_object = GenericForeignKey('content_type', 'object_id')
    viewer = models.ForeignKey(User, verbose_name="Viewer", on_delete=models.CASCADE)
    counted = models.BooleanField(verbose_name="Counted", default=False, editable=True)
    date_added = models.DateTimeField(auto_now=True)

But I'm always falling into the following issue:但我总是陷入以下问题:

'QuerySet' object has no attribute 'object_id' 'QuerySet' 对象没有属性 'object_id'

Of course my Model(s)1-3 containing the field:当然,我的 Model(s)1-3 包含该字段:

hits = GenericRelation(Hit, related_query_name='hit')

Thanks in advance提前致谢

hit = Hit.objects.all() 

is returning a queryset (a "django list" of all the hits), so you cannot do the following正在返回一个查询集(所有命中的“django 列表”),因此您不能执行以下操作

queryset_m1 = Model1.objects.filter(pk=hit.object_id)
queryset_m2 = Model2.objects.filter(pk=hit.object_id)
queryset_m3 = Model3.objects.filter(pk=hit.object_id)

Cause object_id is not an attribute of queryset原因 object_id 不是查询集的属性

You can do something like the following and it should work:您可以执行以下操作,它应该可以工作:

queryset_m1 = Model1.objects.filter(pk__in=hit.filter(content_type_id=id_model_1).values_list('id', flat=True))

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

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