Hulk
Hulk

Reputation: 34160

queries in django

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()

Upvotes: 0

Views: 147

Answers (3)

heaven2sai
heaven2sai

Reputation: 129

employee = Employee.objects.prefetch_related('Add') [emp.Add.all() for emp in employee]

prefetch_related supports many relationships and caches the query set and reduces the database hits hence increases the performance..

Upvotes: 0

fervisa
fervisa

Reputation: 21

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.

Upvotes: 2

Ludwik Trammer
Ludwik Trammer

Reputation: 25022

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.

Upvotes: 5

Related Questions