Search code examples
pythondjangogeneric-foreign-key

FieldError trying to delete Django instances with generic foreign key


While fixing some errors, I made two test instances. Now that I finished that, I wanted to delete those two tests:

nj.delete()
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: awards, career_highlights, content_object_org, content_object_pc, content_type_org, content_type_org_id, content_type_pc, content_type_pc_id, date_updated, daterange, end_date, honors, object_id_org, object_id_pc, org_history_updated, publications, role, significant_event, start_date, title, uniqid, updated_Vitae_bio_and_org_history

This error is not on the model I was deleting from, but an intermediate model which also has a generic foreign key. Django can’t find the field ‘content_type’ because there is no such field, so I don’t know why it is looking for it. There is a content_type_org and a content_type_pc. From the context I assume Django wants the content_type_org. But how do I tell Django to look for that instead? I also tried going to the superclass and deleting the same object from there,

jn.delete()

but got the same error.


Solution

  • As mentioned in the comments, it's difficult to assist without seeing your models. Nevertheless it appears you have renamed the content_type field that is used in the GenericForeignKey. You'll need to specify the renamed field on the related model using a GenericRelation like so:

    class TaggedItem(models.Model):
        
        content_type_fk = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_primary_key = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type_fk', 'object_primary_key')
    
    
    class Blog(models.Model):
        tags = GenericRelation(
            TaggedItem,
            content_type_field='content_type_fk',
            object_id_field='object_primary_key',
        )
    

    See the docs for details.