简体   繁体   中英

Django : Conditional expressions in get_queryset(self)

I am in Django 1.11 and I would like to combine what I read:

For example, suppose I have something like this that will check if Objects are in the user area and a ListView use it.

    open_help_requests = HelpRequest.objects.filter(state=HelpRequest.OPEN)
    filtered_help_requests = []
    for help_request in open_help_requests:
        """ Formule de Haversine pour connaitre la distance entre deux points géographiques """
        earth_radius = 6373.0

        lat1 = radians(help_request.student.studentcollaborator.postal_code.latitude)
        lon1 = radians(help_request.student.studentcollaborator.postal_code.longitude)
        lat2 = radians(request.user.student.studentcollaborator.postal_code.latitude)
        lon2 = radians(request.user.student.studentcollaborator.postal_code.longitude)

        dlon = lon2 - lon1
        dlat = lat2 - lat1

        a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
        c = 2 * atan2(sqrt(a), sqrt(1 - a))

        distance = earth_radius * c
        if distance <= help_request.settings.distance:
            filtered_help_requests.append(help_request)

What I want to move this condition check inside the filter in def get_queryset(self): so that I could directly make additional simple order/filter operations with the filtered QuerySet. Recreate the QuerySet with the filtered variable list id looks too heavy (like this : Django get a QuerySet from array of id's in specific order ).

Any ideas ?

Thanks.

Quite not sure that I'm understanding you well. Anyway,what about creating custom models.QuerySet for your models models.Manager ?

Inside your custom models.QuerySet you can create your own functions for your ordering/filtering goals.

And in your view you can directly get your filtered/ordered list of your objects.

class Foo(models.Model):
    ....
    objects = FooManager()
    ....

class FooManager(models.Manager):
    ....
    def get_queryset(self):
        return FooQuerySet(self.model, using=self._db)
    ....

class FooQuerySet(models.QuerySet):
    ....
    # define your functions here
    # just a simple example
    def order(self, *args, **kwargs):
        return self.filter(
            # you may use Q objects here or whatever 
            ).distinct()
        else:
           return self
    ....

And in your view:

class BarView(ListView):
    ....
    def get_queryset(self):
        ....
        return Foo.objects.all().order(params) # your custom function
        ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM