Django高级过滤 [英] Django Advanced Filtering

查看:125
本文介绍了Django高级过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以根据模型字段的选择过滤查询集吗?

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

模型:

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

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

查看:

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

有没有办法根据不同的颜色选择过滤 Thing ?另外,有没有办法动态写入,所以所有的颜色选择都可以响应单个视图?

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?

推荐答案

想要这个?

查看

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

所以当你访问 http:// yoursite / thisview / black 您将获得 Thing s黑色,当您访问 http:// yoursite / thisview / red 你会得到 Thing s,用红色。

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 .

这篇关于Django高级过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆