Django foreign key and select_related

I am trying to make a model selection using a relationship with a shared foreign key, but it does not work properly.

I think this is better illustrated and understood with code.

class ModelA(models.Model): created = models.DateTimeField(auto_now_add=True) class ModelB(models.Model): instanceA = models.ForeignKey(ModelA) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() class ModelC(models.Model): number = models.PositiveIntegerField() bInstances = generic.GenericRelation(ModelB) # Creating an instance of A and C aInstance=ModelA.objects.create() cInstance=ModelC.objects.create(number=3) # Adding instance of C to the B_set of instance A aInstance.modelb_set.add(content_object=cInstance) # Select all ModelA instances that have C as content object? Does not work whatIWant = ModelA.objects.filter(modelb__content_object=modelCInstance) # Pseudo-solution, requires calling whatIWant.modelA whatIWant = cInstance.bInstances.select_related("modelA") 

To be clear, I would like this line to work: ModelA.objects.filter(modelb__content_object=modelCInstance) , apparently django does not support the use of content_object in filter relationships.

Thanks in advance!

+6
django django-models
source share
1 answer

Take a look at http://www.djangoproject.com/documentation/models/generic_relations/ . And try:

 ctype = ContentType.objects.get_for_model(modelCInstance) what_you_want = ModelA.objects.filter(modelb__content_type__pk=ctype.id, modelb__object_id=modelCInstance.pk) 

Please check out some django coding / naming rules to make your code easier to read and understand!

+9
source share

All Articles