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

[BUG] foreign key with or without `_id`

Open sigma-plus opened this issue 1 year ago • 3 comments

Describe the bug The same foreign key field serializer result changes (with or without _id ) when another api is added.

Versions (please complete the following information):

  • Python version: 3.11.1
  • Django version: 4.2.5
  • Django-Ninja version: 0.22.2
  • Pydantic version: 1.10.12

The minimal setup is :

class TestModel(models.Model):
    department = models.ForeignKey(Department, on_delete=models.CASCADE)


class TestModelSchema(ModelSchema):
    class Config:
        model = models.TestModel
        model_fields = "__all__"


@router.get("/test_model", response=List[TestModelSchema])
def get_test_model(request):
    return models.TestModel.objects.all()

Schema in docs page says the expected results is something like:

[
  {
    "id": 0,
    "department": 0
  }
]

but when I add another api:

@router.put("/test_model/{test_model_id}", response=TestModelSchema)
def update_test_model(request, test_model_id: int, payload: TestModelSchema):
    obj = get_object_or_404(models.TestModel, pk=test_model_id)
    for attr, value in payload.dict().items():
        setattr(obj, attr, value)
    obj.save()
    return obj

department field changes to department_id in both api docs, the real get api result is still department, which is really confusing.

sigma-plus avatar Nov 17 '23 02:11 sigma-plus

updated to 1.0, the bug still exists.

sigma-plus avatar Nov 17 '23 02:11 sigma-plus

Still happening on 1.1

LevonW-IIS avatar Feb 27 '24 19:02 LevonW-IIS

I've the opposite :/

In data I've category_id But in payload.dict() I've category. And since it's a number django throws an error

    raise ValueError(
ValueError: Cannot assign "379": "Software.category" must be a "Category" instance.
image

syabro avatar May 21 '24 02:05 syabro