I'm trying to use generic relations, my model looks like this:
class Post(models.Model):
# Identifiers
user = models.ForeignKey(User, unique=False, related_name = 'posts')
# Resource
resource_type = models.ForeignKey(ContentType)
resource_id = models.PositiveIntegerField()
resource = GenericForeignKey('resource_type', 'resource_id')
# Other
date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True)
class Meta:
unique_together = ('resource_type', 'resource_id',)
However, when on my resource I try to get the Post object, using 'SomeResource.posts
' the following exception occurs:
Cannot resolve keyword 'content_type' into field. Choices are: date_created, id, resource, resource_id, resource_type, resource_type_id, user, user_id
Why is it looking for content_type
when I explicitly named it resource_type
on my GenericForeignKey
?
I don't see it anywhere in the docs right now, but if you look at the source for GenericRelation
there are keywords for content_type_field
and object_id_field
when you create it. So if you create the relation as GenericRelation(object_id_field='resource_id', content_type_field='resource_type')
then it should look for the proper fields.
I found this is particularly necessary if you have multiple GenericForeignKey's
in a single model and thus cannot use the default names.
You can see the source for 1.11 here: https://github.com/django/django/blob/stable/1.11.x/django/contrib/contenttypes/fields.py#L291
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