Your use case sounds very similar to the (now deprecated) Django comments framework. If you check out the models, you'll see how to use a generic relation in BaseCommentAbstractModel
--note that you need all three fields, a ForeignKey
to ContentType
, a field to hold the objects' pk
s, and the GenericForeignKey
field.
As for how to query for objects by GenericForeignKey
, you can see some examples in the template tags in that project. See for example the get_query_set
method in BaseCommentNode
, which retrieves comments by querying on the content type and pk of the target object.
def get_query_set(self, context):
ctype, object_pk = self.get_target_ctype_pk(context)
if not object_pk:
return self.comment_model.objects.none()
qs = self.comment_model.objects.filter(
content_type = ctype,
object_pk = smart_text(object_pk),
site__pk = settings.SITE_ID,
)