Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ForeignKey _id UniqueConstraint discrepancy #9619

Unanswered
kbehlers asked this question in Potential Issue
Discussion options

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()
You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /