Django 查询与 Q 对象?
我有一个模型,
class Employee_Type(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200, verbose_name="employee type")
class Employee(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200)
type = models.ForeignKey(Employee_Type)
address = models.CharField(max_length=500,blank=True, null=True)
telephone = models.CharField(max_length=100, blank=True, null=True)
fax = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(max_length=200, blank=True, null=True)
active = models.BooleanField(default=True)
我需要查询如下内容:
employees = Employee.objects.filter(
Q(name__startswith=key_search) \
& Q(type__icontian= emp_type)#CAN I DO THIS?
Q(active=True)
)
问题:
Q(type__= emp_type) (type = models.ForeignKey(Employee_Type)) I cannot do this.
这里有人请帮助我吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Employee_Type 应重命名为 EmployeeType。这是 Django 模型名称约定。基础表将创建为
appname_employee_type
。对于直接的
and
条件,您不需要 Q() 对象。 Q() 对象对于or
条件或组合and
和or
非常有用。那么您的查询将是:
当然,假设变量 emp_type 包含 EmployeeType 的实例。如果 emp_type 表包含员工类型的名称,请使用:
Employee_Type should be renamed to EmployeeType. This is the Django convention for model names. The underlying table will be created as
appname_employee_type
.You don't need Q() objects for straight
and
conditions. Q() objects are useful foror
conditions, or for combiningand
s andor
s.Then your query will be:
Assuming, of course, the variable emp_type contains an instance of EmployeeType. If the emp_type table contains the name of an employee type, use:
阅读示例 http://www.djangoproject.com/documentation/models/or_lookups/
read example http://www.djangoproject.com/documentation/models/or_lookups/
如果将 Employee_Type 重命名为 Employeetype,则以下操作可能有效:
Employee.objects.filter(employeetype__name=emp_type, name__startswith=key_search, active=True)
(您可以在
filter()<中使用多个条件< /code>,应用 AND 运算符。)
if you rename Employee_Type to Employeetype, following might work:
Employee.objects.filter(employeetype__name=emp_type, name__startswith=key_search, active=True)
(you can use multiple conditions in
filter()
, AND operator is applied.)Q 对象最适合动态查询构建;有关涵盖此主题和其他主题的 Q 对象的教程可以在此处找到:djangos-q-objects 的力量
Q objects a best used for dynamic query building; a tutorial on Q objects covering this and other topics can be found here: the-power-of-djangos-q-objects