问题
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 Thing
s with black color and when you access http://yoursite/thisview/red
you will get Thing
s 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