-
-
Notifications
You must be signed in to change notification settings - Fork 7k
ForeignKey _id
UniqueConstraint discrepancy
#9619
-
Related to #9410 and #7173, so not sure if it belongs as a comment on one of those or should be a separate bug ticket.
The implementation for ModelSerializer generating UniqueConstraints gets circumvented if the UniqueConstraint involves a ForeignKey and the UniqueConstraint.fields uses the syntax without the _id
suffix but the ModelSerializer.Meta.fields uses the syntax with _id
suffix.
It appears to be related to https://github.com/encode/django-rest-framework/pull/7438/files#diff-c33f1f011c9f5cf3ed1357b809ebf2b4ed0b808b227c6c007291bf9b259422ecR1449, which compares field_names
and unique_together_list
without considering that the UniqueConstraint is allowed to include a ForeignKey that doesn't have the _id
suffix.
Minimum Reproducible Example:
from django.db import models class OtherExample(models.Model): pass class Example(models.Model): other_example = models.ForeignKey( to=OtherExample, on_delete=models.CASCADE, ) class Meta: constraints = [ models.UniqueConstraint( fields=[ "id", # "other_example_id", # this questionably raises AssertionError: May not set both `read_only` and `required` "other_example", # this does not raise, but probably should raise something ], name="unique_id_and_other_example", ) ] from rest_framework import serializers class ExampleModelSerializer(serializers.ModelSerializer): # other_example_id = serializers.IntegerField() # another workaround class Meta: model = Example fields = [ "id", "other_example_id", ] from django.test import TestCase class TestExampleModelSerializer(TestCase): def test_unique_constraint(self): ser = ExampleModelSerializer(data={"id": 1, "other_example_id": 1}) assert ser.is_valid()
Beta Was this translation helpful? Give feedback.