Django Using a GenericForeignKey to Reference a Model

ok, so in my database there is a header / line type structure where there are header models that have many row models. This structure exists on many models. I want to keep track of which header models are associated with line models.

Initially, I just had a header model attribute pointing to related models, but I would like it to be stored in the database.

So, I used to use djangos GenericForeignKey, but only when I wanted to have a foreign key relationship with several model samples, and not just the model itself.

Using GenericForeignKeyyou need three things:

content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')

In my case, I don’t need it object_id, but I don’t think I can leave it ...

So, after all this, I think my question is that use GenericForeignKeyis the best way to customize this model or any other solutions.

Another thought was only to use model names ...

hope everything makes sense. thank

+3
source share
1 answer

Since you just want it to point to the models themselves, and not to individual entries, all you need is

my_model = models.ForeignKey(ContentType)

Then, if you want to find out which model the header is associated with, simply

>>> my_header.my_model
<ContentType: Model Name>

, . object_id pk , . content_object , , ( object_id content_type) , , .

+3

Source: https://habr.com/ru/post/1793725/


All Articles