How to use foreignkey with different models in DJango

318 views Asked by At

I'm stack with this problem, and looking for some solution before asking this question here. Lets say I have a one Model that shares same field in different Models how can I achieve this that when I get the objects of those Models I can include that Model foreign key, I did try to achieve this using Generic Relation in DJango yet it didn't solve my issue.

here is the sample what I'm trying to achieve using Generic Relation:

Model1(models.Model):
 .. objects_on_this_model ..

Model2(models.Model):
 .. objects_on_this_model ...

# Now this is where the model I could save different models with same field shared
SameObjectModel(models.Model):
 content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
 object_id = models.PositiveIntengerField()
 content_object = GenericForeignKey('content_type', 'object_id')
 .. objects_on_this_model .. # which is the field that has same field to use in different models

So when I try to get the objects from Model(n) how can I achieve or get the SameObjectModel?

I have this on my mind that I could do this:

Model(n).objects.prefetch_related('fk').all() 

Seems it is not a good idea, since I do not know where I should put the related_name since the foreign key is the content_type which is the model and there is the object_id represent the field primary_key.

1

There are 1 answers

4
Brian Destura On BEST ANSWER

On your Model(n)'s you can add a GenericRelation to SameObjectModel:

from django.contrib.contenttypes.fields import GenericRelation


class Model1(models.Model):
    sameobject = GenericRelation(SameObjectModel)

With this, it should be possible to use prefetch_related:

Model1.objects.prefetch_related('sameobject').all()