[Answered ]-Django models.Model class member not appearing in model_instance._meta.fields

1đź‘Ť

Your are not setting up the generic relation correctly. Read the documentation:

There are three parts to setting up a GenericForeignKey:

  1. Give your model a ForeignKey to ContentType.
  2. Give your model a field that can store a primary-key value from the models you’ll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.)
    This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won’t be able to form a generic relation with a model that uses a CharField as a primary key.
  3. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named “content_type” and “object_id”, you can omit this — those are the default field names GenericForeignKey will look for.

In the end, it must be something like:

content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
👤Felix Kling

1đź‘Ť

Why would you expect it to? It’s not a real field. It’s a virtual field that’s calculated using the (real) content_type and object_id fields on the model.

You can however see it in a._meta.virtual_fields.

Leave a comment