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 eas开发者_如何学编程ily 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?
Check out GenericForeignKey in the built-in contenttypes
framework.
You want Django's generic relations.
精彩评论