Django ForeignKey for any type of model

So, I have a model, a comment. It should contain a link to everything that he comments on. It could be a response to a blog post, or it could be a response to another comment, etc.

So how can I keep this relationship? Generally, I just would like to store information using ForeignKey. But ForeignKey requires him to know the type of model he is referring to.

Is there something built-in in Django like ForeignKey that can reference any type of model? If not, what are the best ways to implement such a relationship?

Here is what I thought:

I could use an integer to store the identifier of the object it responds to, and then CharField to store the type, and then I would get the object by doing something like globals()[type_name].objects.get(id=id), but I think I will have problems in the future if I Ever needed to do anything complicated, like searching, if I used this method.

Alternatively, I could create another class of comments for each object that it could respond to (automatically, of course). But then again, this causes limitations. I could no longer easily do things likeComment.objects.get(id=5)

Or I could have my comment class have a ForeignKey for every possible thing he could answer, leaving only 1 zero for each comment. It still seems like this is a sub-pair solution.

Suggestions?

+3
2

GenericForeignKey contenttypes.

+4

Django .

+2

All Articles