Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Using GenericForeignKey to reference a model

Tags:

django

models

ok, so my database has a headers/lines type structure, where there is header models which have many lines models. This structure is in place on many models. I want to keep track of which header models are related to which lines models.

Originally I simply had an attribute on the header model pointing to the related models, but would like this to be stored in the database.

So I have used djangos GenericForeignKey stuff before, but only when I wanted to have foreign key relationships with several model records, not just the model themselves.

With the GenericForeignKey you have three things needed:

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

In my case, I dont need the object_id but I dont think that I can leave it out...

So after all that I guess my question is if using GenericForeignKey is the best way of setting up this model, or are there any other solutions.

Another thought was just to use the model names...

hopefully that all makes sense. thanks

like image 502
neolaser Avatar asked Sep 15 '26 01:09

neolaser


1 Answers

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

my_model = models.ForeignKey(ContentType)

Then, if you want to figure out which model a header is associated with, just do

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

If you want to point to specific records, you need the other two fields. The object_id field holds the pk of the record you're pointing too. And the content_object field is NOT stored in the database, but rather is just a nice wrapper that (using the object_id and content_type fields) returns the model object, rather than you having to look up the record manually based on the content type and the id.

like image 130
Andrew C Avatar answered Sep 16 '26 14:09

Andrew C