Django Advanced Filtering

拟墨画扇 提交于 2019-12-10 11:36:32

问题


Can I filter a queryset based on a model field's choices?

model:

COLORS = (
    ('BLACK', 'black'),
    ('RED', 'red'),
    ('BLUE', 'blue'),
    //etc..
)

class Thing(Models.model):
    color = models.CharField(max_length=5, choices=COLORS)

view:

def filter_by_color(request):
    q = Thing.objects.filter(???) 

Is there a way to filter Thing based on different color choices? Also, is there a way to write this dynamically, so that all color choices can respond to a single view?


回答1:


Do you want this?

view

def filter_by_color(request, color):
     q = Thing.objects.filter(color=color)

So when you access http://yoursite/thisview/black you will get Things with black color and when you access http://yoursite/thisview/red you will get Things with red color .




回答2:


You should look into Q objects. That can help you construct complex OR queries depending on what colors the user is choosing to filter on.

UPDATE Adding an example.

Assuming that you want to filter on more than one color:

from django.db.models import Q

def filter_by_color(request):

    q = Thing.objects.filter(Q(color="BLACK") | Q(color="RED))

UPDATE 2 If the user selects the colors with checkboxes or similar you can use this approach:

def filter_by_color(request):
    selected_colors = request.GET.getlist('colors')

    q = Thing.objects.filter(color__in=selected_colors)


来源:https://stackoverflow.com/questions/13133707/django-advanced-filtering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!