Django - how to build a GenericRelation query?

690 views Asked by At

I'm trying to access all my different model objects by the Hit table. 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.

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:

...

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'

Of course my Model(s)1-3 containing the field:

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

Thanks in advance

1

There are 1 answers

9
Roberto Fernandez Diaz On
hit = Hit.objects.all() 

is returning a queryset (a "django list" of all the hits), so you cannot do the following

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

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