feat: add contains() operation to QuerySet#2163
feat: add contains() operation to QuerySet#2163seladb wants to merge 10 commits intotortoise:developfrom
contains() operation to QuerySet#2163Conversation
contains() operation to QuerySetcontains() operation to QuerySet
|
@abondar MSSQL tests fail randomly, but shouldn't be related to the changes in this PR |
contains() operation to QuerySetcontains() operation to QuerySet
|
@abondar this PR is ready for review, can you please take a look? 🙏 |
@abondar @waketzheng a gentle reminder that this PR is ready for review. Do you think you can take a look? |
|
@abondar this PR is open for a while, can you please review it? |
| use_indexes=self._use_indexes, | ||
| ) | ||
|
|
||
| def contains(self, obj: MODEL) -> ContainsQuery: |
There was a problem hiding this comment.
It seems like we should add validations around obj here, so that it is same type as queryset, and it's obj.pk is not None - in other case passing such objects can lead to strange behavior
There was a problem hiding this comment.
@abondar I'm not sure we have to have to verify the object has the same type as the queryset because we have that in the type-hint, but I can add it if you think it's needed:
There was a problem hiding this comment.
Checking if obj.pk exists was added in 7ace03c
There was a problem hiding this comment.
I am concerned about case where object of other model would be passed and it will silently try to check against that other model id, maybe even returning True, which is definetely not what we want
| pk_attr = self.model._meta.pk_attr | ||
| source_pk_attr = self.model._meta.fields_map[pk_attr].source_field or pk_attr | ||
| pk = Field(source_pk_attr) | ||
| self.query = self.query.where(pk.eq(self._obj.pk)) |
There was a problem hiding this comment.
pk_value = self.model._meta.fields_map[pk_attr].to_db_value(self._obj.pk, None) - we need to add conversion, to be better ready for custom id types
There was a problem hiding this comment.
Also we have self.model._meta.db_pk_column - to use it directly instead of calculating
There was a problem hiding this comment.
You didn't changed it to use "to_db_value" - is it intentional?
Add
QuerySet.contains()method for checking if object exists in querysetDescription
Added
QuerySet.contains()which checks if a specific model instance exists within a queryset. Implementation includes:QuerySet.contains(obj)method intortoise/queryset.pythat returns aContainsQueryobjectContainsQueryclass that extendsExistsQueryand adds filtering by the object's primary keyMotivation and Context
This feature enables checking if a specific model instance belongs to a filtered queryset, useful for membership checks without fetching the full object.
It's also in par with Django API.
How Has This Been Tested?
test_containsintests/test_queryset.pycovering all casesChecklist: