Question:
How to find an alternative way of Q object?

Problem

Anyone can tell me if, have any alternative way of doing it? I actually searched for a more optimized way than it.


def get_queryset(self):

        return self.queryset.filter(Q(email="") | Q(phone="")).order_by("name")


phone and email fields are:


phone = models.CharField(max_length=20, blank=True)

email = models.EmailField(blank=True)


Solution

I would advice to try a ">UNION".

  

def get_queryset(self):

        qs1 = self.queryset.filter(email="")

        qs2 = self.queryset.filter(phone ="")

        return qs1.union(qs2).order_by("name")


In some cases, it seems that UNION can be more optimized than OR.

You have a >very good question about this in StackOverflow


Answered by: >0urz4g

Credit: >StackOverflow


Blog Links

>How to manage the Text in the container in Django?

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from the website

>Sending Audio file from Django to Vue

>How to keep all query parameters intact when changing page in Django?

>Solved: TaskList View in Django

>Implement nested serializers in the Django rest framework

>How to filter events by month in Django?

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers