1

If we have model like

class SomeModel(models.Model):
 field_1 = models.IntegerField()
 field_2 = models.IntegerField()

and in every query for a given value if we have to check against both the fields, is it possible to simplify the redundancy (field_1=value, field_2=value) using a custom Manager ?

SomeModel.objects.filter(Q(field_1=value) | Q(field_2=value))
SomeModel.objects.filter(Q(field_1=value) | Q(field_2=value)).count()
asked Feb 4, 2020 at 21:53
2
  • Given you each time need to do that, is there a situation where field_1 and field_2 have a different value? Commented Feb 4, 2020 at 21:57
  • Good catch. No they will never be the same and its the or condition instead of and. Commented Feb 4, 2020 at 22:00

1 Answer 1

1

Yes, you can make a mananger, like:

class SomeModelManager(models.Manager):
 def with_value(self, value):
 return self.get_queryset().filter(field_1=value, field_2=value)

or with an or-condition:

from django.db.models import Q
class SomeModelManager(models.Manager):
 def with_value(self, value):
 return self.get_queryset().filter(Q(field_1=value) | Q(field_2=value)

We can then add the manager to the SomeModel model:

class SomeModel(models.Model):
 field_1 = models.IntegerField()
 field_2 = models.IntegerField()
 object = SomeModelManager()

Then you can access the filtered queryset with:

SomeModel.objects.with_value(value)
SomeModel.objects.with_value(value).count()
answered Feb 4, 2020 at 21:59
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.