Movatterモバイル変換


[0]ホーム

URL:


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

Fix unique together validator doesn't respect condition's fields#9360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged

Conversation

kalekseev
Copy link
Contributor

fixes#9358

joaodaher reacted with thumbs up emoji9128305 and joaodaher reacted with eyes emoji
@tomchristie
Copy link
Member

@kalekseev - Could you talk me through this?

My understanding is that it's resolving an issue in#7438, is that correct?

@kalekseev
Copy link
ContributorAuthor

kalekseev commentedMay 16, 2024
edited
Loading

@kalekseev - Could you talk me through this?

My understanding is that it's resolving an issue in#7438, is that correct?

UPDATE: Yes, this pr is supposed to fix the initial implementation of UniqueConstraint support but at the moment it doesn't work. The problem is that DRF doesn't check if fields in data match the unique constraint condition or not, so for example constraint is:

            models.UniqueConstraint(                name="unique_constraint_model_together_uniq2",                fields=('race_name', 'position'),                condition=models.Q(fancy_conditions__gte=10),            )

we have record in db that should be unique

        UniqueConstraintModel.objects.create(            race_name='condition',            position=1,            global_id=10,            fancy_conditions=10        )

The data below should be valid because it hasfancy_conditions=9 that doesn't match constraint conditionmodels.Q(fancy_conditions__gte=10):

       serializer = UniqueConstraintSerializer(data={            'race_name': 'condition',            'position': 1,            'global_id': 11,            'fancy_conditions': 9,        })

but this should fail

      serializer = UniqueConstraintSerializer(data={            'race_name': 'condition',            'position': 1,            'global_id': 11,            'fancy_conditions': 11,        })

@kalekseevkalekseevforce-pushed thefix-unique-together-condition branch fromfcc7c8d to472a323CompareMay 17, 2024 00:08
@kalekseevkalekseevforce-pushed thefix-unique-together-condition branch 3 times, most recently from0a64365 to9b7db30CompareJune 23, 2024 14:56
@kalekseev
Copy link
ContributorAuthor

@kalekseev - Could you talk me through this?

My understanding is that it's resolving an issue in#7438, is that correct?

@tomchristie I think this PR is ready for review, I described issue in previous comment, the fix is here

https://github.com/encode/django-rest-framework/pull/9360/files#diff-9240f7dfb9eb2cace23eef00e4c922d6e2b6e85dc58b3c9d804e78c6c6227614R27-R34 the rest is just support code to perform that check (make sure that conditional fields values are present in serializer to perform check against condition).

The condition check is actually copy of code fromhttps://github.com/django/django/blob/7ba2a0db20c37a5b1500434ca4ed48022311c171/django/db/models/constraints.py#L672

@auvipy
Copy link
Member

we have this separate PR which seems to fix a regression, can you guys please check?#9482

@MaxNstk
Copy link

MaxNstk commentedSep 30, 2024
edited
Loading

I do not know how the situation is right now but I noticed that when upgrading from the 3.14.0 version to 3.15.2 my condition started to broke. Here is the model:

`
class DailyDataRecord(SynchronizationRecord):

date = models.DateField(verbose_name='Data')is_active = models.BooleanField(default=False,verbose_name='Ativo')class Meta:    ordering= ['-date']    verbose_name='Registro diário'    verbose_name_plural='Registros diários'    abstract=True    constraints = [        models.UniqueConstraint(            fields=['date'],            condition=models.Q(is_active=True),            name='%(app_label)s_%(class)s_unique_active_dailyrecord_for_date'        )    ]

`

In the current state it stops to check the condition is_active=True and raises and exception if I try to create a new record with is_active=False for the same date.
Ps. The serializer is just a normal ModelSerializer with any model that extends of this class

@SorianoMarmol
Copy link

Is a new version expected with this fix and others related like#9531? The support for UniqueConstraint is not complete and may cause issues…

Copy link
Member

@auvipyauvipy left a comment
edited
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

can you please re base again? we got a separate PR merged

Copy link
Member

@pauloxnetpauloxnet left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This PR looks ready to be merged (after the rebase), but I've added a few code suggestions.

None of the suggestions are blocking (except maybe removingprint in the tests) but in general they all serve the purpose of improving the code itself, or the Git history.

Copy link
Member

@auvipyauvipy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

we need to fix the following failing test as well

FAILED tests/test_validators.py::TestUniqueConstraintValidation::test_unique_together_condition_fields_required
=========== 1 failed, 1542 passed, 13 skipped, 5 warnings in 18.20s ============
py38-django42:

@kalekseevkalekseevforce-pushed thefix-unique-together-condition branch 3 times, most recently from2fd3b45 to71ba738CompareFebruary 16, 2025 14:06
@kalekseev
Copy link
ContributorAuthor

@auvipy rebased

@auvipyauvipy self-requested a reviewFebruary 16, 2025 18:00
Copy link
Member

@auvipyauvipy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

what do you think about this change?

@kalekseevkalekseevforce-pushed thefix-unique-together-condition branch from71ba738 to59dd379CompareFebruary 17, 2025 07:55
@auvipyauvipy merged commit17e9560 intoencode:masterFeb 17, 2025
8 checks passed
@tomchristie
Copy link
Member

@auvipy No. I'm not comfortable with the way this has been merged, completely unclear behavior.

@auvipy
Copy link
Member

ops! Ok sorry! I thought comments were addressed! Going to revert this ASAP

@tomchristie
Copy link
Member

Please do. We're really clear on#9130

This project should be neatly parked.

@kalekseev
Copy link
ContributorAuthor

@tomchristie@auvipy I believe I addressed all comments as good as I can. If you have direct question I'm ready to answer them while I'm on that.

@auvipy
Copy link
Member

Please do. We're really clear on#9130

This project should be neatly parked.

It was a django orm compatibility PR. But doing anyway

@tomchristie
Copy link
Member

We're really clear on#9130

This project should be neatly parked.

@browniebroke
Copy link
Member

I thought that this PR fitted in the first category "Tracking any changes required by updates in Django versions" as Django replacesunique_together with the most powerful constraints API.

stianjensen, auvipy, and sevdog reacted with thumbs up emoji

@encodeencode deleted a comment fromdetetiveselvagemFeb 17, 2025
@sipa-echo-zaoa
Copy link

Hi@kalekseev, thank you for your work.

I think I found an issue in the way the serializer fields validator are being generated.
In my case I have the UniqueConstraint on fields that are foreign key and I see that the UniqueConstraint validators are not being generated for them.
I tried cloning the repository and modifying the models used in TestUniqueConstraintValidation test case by changing
fancy_conditions into a ForeignKey instead of IntegerField.

class FancyConditionModel(models.Model):    id = models.AutoField(primary_key=True)class UniqueConstraintModel(models.Model):    race_name = models.CharField(max_length=100)    position = models.IntegerField()    global_id = models.IntegerField()    fancy_conditions = models.ForeignKey(FancyConditionModel, null=True, on_delete=models.CASCADE)

Trying running the tests result in the following errors:

FAILED [100%]tests/test_validators.py:624 (TestUniqueConstraintValidation.test_single_field_uniq_validators)0 != 4Expected :4Actual   :0<Click to see difference>test_validators.py:640: in test_single_field_uniq_validators    assert len(validators) == 2 + extra_validators_qtyE   assert 0 == (2 + 2)E    +  where 0 = len([])

Is this an expected behaviour or am I missing something?

9128305 reacted with eyes emoji

@browniebroke
Copy link
Member

Do you think you could start a pull request with a failing test reproducing your problem? That might help us get the conversation going...

auvipy reacted with thumbs up emoji

@sipa-echo-zaoa
Copy link

Hi@browniebroke I've created the#9678 merge request reproducing the problem.
Let me know if you need further information.

browniebroke reacted with thumbs up emoji

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@pauloxnetpauloxnetpauloxnet left review comments

@sevdogsevdogsevdog left review comments

@auvipyauvipyauvipy approved these changes

@SorianoMarmolSorianoMarmolSorianoMarmol approved these changes

@browniebrokebrowniebrokeAwaiting requested review from browniebroke

Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

9 participants
@kalekseev@tomchristie@auvipy@MaxNstk@SorianoMarmol@browniebroke@sipa-echo-zaoa@pauloxnet@sevdog

[8]ページ先頭

©2009-2025 Movatter.jp