django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[BUG] Facing issue with GenericForeignKey field

Open ganeshprasadrao opened this issue 2 years ago • 3 comments

Facing issue while serializing a model with GenericForeignKey My model looks something like this:

class MyModel(models.Model):
    obj_content_type = models.ForeignKey(
        ContentType, null=True, blank=True,
        related_name='notify_object', on_delete=models.CASCADE,
        verbose_name=_('Content type of action object'))

    obj_object_id = models.PositiveIntegerField(
        null=True, blank=True,
        verbose_name=_('ID of the target object'))
    obj_content_object = GenericForeignKey('obj_content_type', 'obj_object_id')

My Schema:

class MyModelSchema(ModelSchema):
    class Config:
        model = MyModel
        model_fields = '__all__'

The exception occurs at:

ninja/orm/fields.py", line 110, in get_schema_field
    internal_type = field.related_model._meta.pk.get_internal_type()
AttributeError: 'NoneType' object has no attribute '_meta'

Versions

  • Python version: 3.8.10
  • Django version: '4.1.5'
  • Django-Ninja version: '0.21.0'
  • Pydantic version: '1.10.6'

ganeshprasadrao avatar Mar 18 '23 07:03 ganeshprasadrao

Hi @mister-rao

Good question...

what is your schema expectation for GenericForeignKey ?

vitalik avatar Mar 19 '23 08:03 vitalik

I'm not including the field in schema. I'm using it to map objects for querying. To overcome the error, I'm currently using model_exclude

class Config:
        model = MyModel
        model_exclude = ("obj_content_object",)

We could skip resolving GenericForeignKey field during schema generation.

ganeshprasadrao avatar Mar 19 '23 08:03 ganeshprasadrao

Excluding GenericForeignKey fields also doesn't work. Throws the following error:

ninja.errors.ConfigError: DjangoField(s) {'<FieldName>'} are not in model <class 'app.models.Subscription'>

unique1o1 avatar Feb 24 '24 06:02 unique1o1