django-tables2 中的多对多

many to many in django-tables2

我通过 ForeignKey 拥有多对多的 django 模型:

    class A(m.Model):
        id = m.AutoField(primary_key=True)
        name = m.CharField(max_length=250, unique=True, null=False)

        def __str__(self):
            return self.name


    class B(m.Model):
        id = m.AutoField(primary_key=True)
        name = m.CharField(max_length=250, unique=True, null=False)
        a = m.ForeignKey(A)

        def __str__(self):
            return self.name


    class C(m.Model):
        id = m.IntegerField(null=False, unique=True, primary_key=True)
        name = m.CharField(max_length=250, unique=True, null=False)
        bs = m.ManyToManyField(B, through='D')

        def __str__(self):
            return '%d, %s, (%s), (%s)' % (
                self.id,
                self.name, 
                ', '.join(b.name for b in self.bs.all()), 
                ', '.join(b.a.name for b in self.bs.all()))
                )


    class D(m.Model):
        c = m.ForeignKey(C)
        b = m.ForeignKey(B)

        class Meta:
            unique_together = ('c', 'b')

django-tables2 来自模型 C:

class CTable(tables.Table):

    class Meta:
         model = C

观看次数:

def C(request):
    data = C.objects.all()
    c_table = t.CTable(data)
    return render(request, 'c.html', {'c_table': c_table})

并在 c.html 中:

...
    {% render_table c_table %}
...

我得到的 table 只有两列 (id, name) 而不是四列 (id, name, b.name, b.a.name)。 如何从多对多中获取缺失的列? 对不起我糟糕的英语。

在模型中添加一个属性方法,使用tableclass渲染,即:

型号class

class C(m.Model):
    id = m.IntegerField(null=False, unique=True, primary_key=True)
    name = m.CharField(max_length=250, unique=True, null=False)
    bs = m.ManyToManyField(B, through='D')

    def __str__(self):
        return '%d, %s, (%s), (%s)' % (
            self.id,
            self.name, 
            ', '.join(b.name for b in self.bs.all()), 
            ', '.join(b.a.name for b in self.bs.all()))
            )

   @property
   def all_bs(self):
      return ', '.join([x.name for x in self.bs.all()])

Table class

class CTable(tables.Table):

    class Meta:
         model = C
         fields = ('a', 'b', 'all_bs')