[英]many to many in django-tables2
I have django's models with many to many through ForeignKey: 我通过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 from model C: 来自模型C的django-tables2:
class CTable(tables.Table):
class Meta:
model = C
views: 观点:
def C(request):
data = C.objects.all()
c_table = t.CTable(data)
return render(request, 'c.html', {'c_table': c_table})
and in c.html: 并在c.html中:
...
{% render_table c_table %}
...
I get table with only two columns (id, name) instead four (id, name, b.name, baname). 我得到的表只有两列(id,name),而不是四列(id,name,b.name,baname)。 How to get the missing columns from many to many?
如何获得多列缺失的列? Sorry for my terrible english.
对不起,我的英语不好。
Add a property method in the model and render it using table class, ie: 在模型中添加一个属性方法,并使用表类来呈现它,即:
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()])
class CTable(tables.Table):
class Meta:
model = C
fields = ('a', 'b', 'all_bs')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.