基于动态属性的django查询() [英] django query based on dynamic property()

查看:251
本文介绍了基于动态属性的django查询()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以使用动态生成的python属性使用 property()在查询集上使用Django的filter()。我有每个用户的 first_name last_name ,我想根据连接名称 first_name last_name 。 (原因在于,当我自动完成自动完成时,我会搜索以查看查询是否与名字,姓氏或连接的一部分相匹配。我想要 John S

我创建了一个名称

  def _get_name(self):
return self.first_name ++ self.last_name
name = property(_get_name)

这样我可以调用用户



但是,如果我尝试执行 User.objects.filter(name__istartswith = query)我收到错误无法将关键字'name'解析为字段。



任何有关如何做的想法?我必须在数据库中创建另一个字段来存储全名?

解决方案

filter()在数据库级别(它实际写入SQL)操作,因此无法将其用于任何que基于你的python代码(你的问题的动态属性)



这是一个从许多其他答案在这个部门:)


I was wondering if there was a way to use Django's filter() on query sets using a dynamically generated python property using property(). I have first_name and last_name of every user, and I want to filter based on their concatenated name first_name last_name. (The reason behind this is that when I do autocomplete I search to see if the query matches first name, last name, or part of the concatenation. I want John S to match John Smith, for example.

I created a property of name:

def _get_name(self):
    return self.first_name + " " + self.last_name
    name = property(_get_name)

This way I can call user.name to get the concatenated name.

However, if I try to do User.objects.filter(name__istartswith=query) I get the error Cannot resolve keyword 'name' into field.

Any ideas on how to do this? Do I have to create another field in the database to store the full name?

解决方案

filter() operates on the database level (it actually writes SQL), so it won't be possible to use it for any queries based on your python code (dynamic property in your question).

This is an answer put together from many other answers in this department : )

这篇关于基于动态属性的django查询()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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