Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve keyword 'content_type' into field

Tags:

django

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?

like image 326
Sebastian Olsen Avatar asked Sep 13 '16 13:09

Sebastian Olsen


1 Answers

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

like image 109
Alec Peters Avatar answered Oct 06 '22 06:10

Alec Peters