Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django ForeignKey to any type of model

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?

like image 772
Ponkadoodle Avatar asked May 09 '11 01:05

Ponkadoodle


People also ask

What is ForeignKey Django models?

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.

What's the difference between Django OneToOneField and ForeignKey?

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 .

How does Django implement one to many relationship?

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).

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.


2 Answers

Check out GenericForeignKey in the built-in contenttypes framework.

like image 71
Sam Dolan Avatar answered Sep 18 '22 02:09

Sam Dolan


You want Django's generic relations.

like image 23
Matt Howell Avatar answered Sep 20 '22 02:09

Matt Howell