select_related与通过表自定义的多对多关系 [英] select_related on many to many with custom through table

查看:104
本文介绍了select_related与通过表自定义的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型Foo和Bar,并且我通过表FooBar与自定义创建了多对多关系。

I have two models, Foo and Bar, and I have created a many to many relationship with a custom through table, FooBar.

class Foo(models.Model):
    foofield = models.CharField()

class Bar(models.Model):
    barfield = models.CharField()
    foos = models.ManyToManyField('Foo', through='FooBar', related_name='foo_bar')

class FooBar(models.Model):
    foo = models.ForeignKey(Foo, related_name='foobar')
    bar = models.ForeignKey(Bar, related_name='foobar')
    foobarfield= models.CharField()

我想做的是显示给定实例Foo的所有Bar记录,并且对于每个这样的记录,还显示foobarfield的对应值。所以我会得到类似的东西

What I would like to do is display all Bar records for a given instance of Foo, and for each such record also display the corresponding value of foobarfield. So I would get something like


  1. barfield_value1,foobarfield_value1

  2. barfield_value2,foobarfield_value2

  3. barfield_value3,foobarfield_value3

  4. ...

  1. barfield_value1, foobarfield_value1
  2. barfield_value2, foobarfield_value2
  3. barfield_value3, foobarfield_value3
  4. ...

我不能似乎构造正确的查询来做到这一点。我尝试过类似的

I can't seem to construct the correct query to do this though. I tried something like

Bar.objects.select_related('foobar').filter(foobar__foo = foo_instance)

因为我希望foobar对于Foo的给定实例是唯一的,但这似乎不起作用。如何获得所需的结果?

Since I would expect foobar to be unique for a give instance of Foo but this does not seem to work. How do I get the result I want?

推荐答案

由于您在<$ c $中的每一相关行都会得到一个结果c> FooBar 表,并且由于您要访问该表上的字段( foobarfield ),最直接的方法是对 FooBar

Since you will have one result for every related row in the FooBar table, and since you want to access fields on that table (foobarfield), the most straightforward approach is to filter on FooBar:

foobars = FooBar.objects.select_related("bar").filter(foo=foo_instance)
for foobar in foobars:
    print(foobar.bar.barfield, foobar.foobarfield)

这篇关于select_related与通过表自定义的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆