It is necessary to obtain an instance of class A, according to the instances of B. attached to it.

class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A) content_type = models.ForeignKey(ContentType) object_id = models.IntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') 

I'm trying to do this:

 instances = { '1':10, '2':20, '3':30 } for ct, id in instances.items(): qset |= Q(content_type=int(ct), object_id=int(id)) a = A.objects.all().select_related().filter(qset) 

I get the error:

Cannot resolve keyword 'object_id' into field.

If so:

 a_all = A.objects.all() for a in a_all: print a.a_set.filter(qset) 

That works, but not quite as it should.

Actually, the question is: how can I get an instance of class A according to the exact occurrence of instances of class B attached to it?

  • Would you write headlines in the yellow press :) - ReinRaus
  • Thank you, but why in the blue? :) - Yury Andreev

2 answers 2

 a = A.filter(b__in=queryset) 

where queryset set of b instances to search for.

If not, then reformulate the question. Because it is not very clear.

  • Thank you, your answer pushed me to thinking in the right direction. Many thanks! - Yury Andreev

After much deliberation, I did this:

 links = {} for a in A.objects.filter(base=base): aid = str(a.id) links[aid] = [] for ct, id in instances_kwargs.items(): lnk = get_object_or_None(B, a=a, content_type=int(ct), object_id=int(id)) if lnk is not None: links[aid].append(lnk) else: del links[aid] break; 

As a result, we obtain all B-instances associated with this A-instance that strictly correspond to the incoming comparison dictionary. Instances_kwargs