views:

68

answers:

2

How to query Employee to get all the address related to the employee, Employee.Add.all() does not work..

 class Employee():
    Add = models.ManyToManyField(Address)
    parent = models.ManyToManyField(Parent, blank=True, null=True)

class Address(models.Model):
   address_emp = models.CharField(max_length=512)
   description = models.TextField()

   def __unicode__(self):
   return self.name()
+5  A: 

Employee.objects.get(pk=1).Add.all()

You need to show which employee do you mean. pk=1 is obviously an example (employee with primary key equal to 1).

BTW, there is a strong convention to use lowercase letters for field names. Employee.objects.get(pk=1).addresses.all() would look much better.

Ludwik Trammer
+1  A: 

Employee.Add.all() does not work because you are trying to access a related field from the Model and this kind of queries require an instance of the model, like Ludwik's example. To access a model and its related foreign key field in the same query you have to do something like this:

Employee.objects.select_related('Add').all()

That would do the trick.

fernando.visa