Search code examples
djangodjango-q

Django Query with Q object?


I have a model

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) 

I need to query something like this:

 employees = Employee.objects.filter(
                            Q(name__startswith=key_search) \
                            & Q(type__icontian= emp_type)#CAN I DO THIS?
                            Q(active=True)                            
                            )

Problems:for

Q(type__= emp_type) (type = models.ForeignKey(Employee_Type)) I cannot do this.

Anybody here Please help me?


Solution

  • 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 for or conditions, or for combining ands and ors.

    Then your query will be:

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

    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:

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