1

我有一个模型

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.

有人在这里请帮助我吗?

4

4 回答 4

7

Employee_Type 应重命名为 EmployeeType。这是模型名称的 Django 约定。基础表将创建为appname_employee_type.

and对于直接条件,您不需要 Q() 对象。Q() 对象对于or条件或组合ands 和ors 很有用。

那么您的查询将是:

employees = Employee.objects.filter(name__startswith=key_search, 
                                    type=emp_type, 
                                    active=True)                            

当然,假设变量 emp_type 包含 EmployeeType 的一个实例。如果 emp_type 表包含员工类型的名称,请使用:

employees = Employee.objects.filter(name__startswith=key_search, 
                                    type__name=emp_type, 
                                    active=True)                            
于 2009-12-18T04:46:44.490 回答
1

如果您将 Employee_Type 重命名为 Employeetype,以下可能会起作用:

Employee.objects.filter(employeetype__name=emp_type, name__startswith=key_search, active=True)

(您可以在 中使用多个条件filter(),应用 AND 运算符。)

于 2009-12-18T04:27:27.147 回答
1

阅读示例http://www.djangoproject.com/documentation/models/or_lookups/

于 2009-12-18T04:44:59.643 回答
0

Q 对象最适合用于动态查询构建;可以在此处找到有关此主题和其他主题的 Q 对象教程:the-power-of-djangos-q-objects

于 2011-10-19T20:18:11.587 回答