是否有任何可接受的方法可以在不使用 API 的情况下切割/重新组合 Django 查询集?
我被迫使用 models.CharField 在我的模型之一中存储一些附加标志。所以我滥用该字段的每个字母作为标志。例如,“MM5”表示“男性,已婚,年龄超过 50 岁”,“FS2”表示“女性,单身,年龄超过 20 岁”。
我正在使用方法来查询/访问这些标志。当然,我不能将这些方法与查询集 API 一起使用。我使用列表推导式调用方法来过滤初始查询集并将其转换为普通列表,这对于大多数模板馈送来说已经足够了:
people = People.objects.filter(name__startswith='J')
people_i_want = [p for p in people if p.myflags_ismale() and p.myflags_isolderthan(30)]
那么,有没有什么好的方法可以将这些列表重新转换回查询集?或者根据我的方法的输出来截取/过滤查询集,而不首先将其转换为普通列表?
I was to forced to use a models.CharField to store some additional flags in one of my models. So I'm abusing each letter of the field as a flag. As an example, 'MM5' would mean "man, married, age above 50" and 'FS2' "female, single, age above 20".
I'm using methods to query/access these flags. Of course I cannot use these methods with the queryset API. I'm using list comprehensions calling the methods to filter an initial queryset and transform them into a plain list, which is good enough for most template feeding:
people = People.objects.filter(name__startswith='J')
people_i_want = [p for p in people if p.myflags_ismale() and p.myflags_isolderthan(30)]
So, is there any ok'ish way to retransform these lists back into a queryset? Or to chop/filter a queryset based on the output of my methods without transforming it to a normal list in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果必须将列表转换回查询集,那么我使用的习惯用法是:
显然,这会再次访问数据库。但如果你真的需要的话。
If you must convert a list back into a queryset, then the idiom I use is:
Obviously, this hits the database again. But if you really need it.
尝试将列表“重新转换”回 QuerySet 可能会不必要地复杂,并且是不好的做法,最好的办法是使用更聪明的 QuerySet 过滤。
您应该通过
regex
语法使用查询集过滤器来获取您需要的功能。 此处的文档。例如,使用
regex
相当于ismale()
,类似于...Also, while I'm admittedly not a database guru, I'm fairly certain using this sort of "flags" in a charfield is a rather inefficient way of doing things.
It would probably be needlessly complicated as well as bad practice to try and "re-transform" your list back into a QuerySet, the best thing to do is to use cleverer QuerySet filtering.
You should use the queryset filter by
regex
syntax to get the functionality you need. Documentation here.For instance the equivalent to
ismale()
usingregex
would be something like...Also, while I'm admittedly not a database guru, I'm fairly certain using this sort of "flags" in a charfield is a rather inefficient way of doing things.