So I have a model, Comment. In it, it must keep a reference to whatever it's commenting to.
It can be a response to a blog post, or it can be a response to another comment, etc.
So how do I go about storing that relationship? Typically, I would just store the information with a ForeignKey. But a ForeignKey requires that it know the type of model it's referencing.
Is there something built into Django like a ForeignKey that can reference any type of model? If not, what are the best ways of implementing such a relationship?
Here's what I've thought of:
I could use an integer to store the id of the object that it is responding to, and then a CharField to store the type and then I would obtain the object by doing something like globals()[type_name].objects.get(id=id)
but I think I would have some problems down the road if I ever needed to do anything complex like searching if I used that method.
Alternatively, I could create a different Comment class for each object that it could be responding to (automatically, of course). But again, that causes limitations. I could no longer easily do things like Comment.objects.get(id=5)
Or I could have my comment class have a ForeignKey for each possible thing it could be responding to, leaving all but 1 null for each comment. Still seems like a sub-par solution.
Suggestions?
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .
To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model).
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
Check out GenericForeignKey in the built-in contenttypes
framework.
You want Django's generic relations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With