Reputation: 21721
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?
Upvotes: 0
Views: 4423
Reputation: 4234
Q objects are best used for dynamic query building; a tutorial on Q objects covering this and other topics can be found here: The power of django's Q objects
Upvotes: 2
Reputation: 6394
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 and
s and or
s.
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)
Upvotes: 8
Reputation: 19905
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.)
Upvotes: 1
Reputation: 11
read example http://www.djangoproject.com/documentation/models/or_lookups/
Upvotes: 1