开发者

queries in django

开发者 https://www.devze.com 2022-12-26 10:53 出处:网络
How to query Employee to get all the address related to the employee,Employee.Add.all()does not work..

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开发者_如何学Go self.name()


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.


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.


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..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号