【发布时间】:2021-07-15 06:52:04
【问题描述】:
因此,我想在我的项目中以多对多关系将两个应用程序链接在一起。
第一个应用程序由以下模型描述。
model.py:
class ChannelCategory(models.Model):
name = models.CharField(max_length=200, db_index=True)
def __str__(self):
return '%s' % self.name
class Channel(models.Model):
category = models.ForeignKey(ChannelCategory, on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
class Meta:
ordering = ['category']
def __str__(self):
return '%s (%s)' % (self.category, self.name)
第二个应用由以下模型描述
class Tariff(models.Model):
channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False)
def __str__(self):
return '%s' % self.name
def get_channels_categories(self):
return ([str(p.category) for p in self.channels_list.all()])
def get_channels_objects(self):
return ([str(p.name) for p in self.channels_list.all()])
现在我想做什么?假设资费对象包含4个渠道,有不同的类别,我们大致得到如下图:资费A有4个渠道来自2 个不同的渠道类别,例如“超级”资费有
['ChannelCategory_1: Channel_1', 'ChannelCategory_1: Channel_3', 'ChannelCategory_2: Channel_2', 'ChannelCategory_2: Channel_4']
我不明白如何在界面上正确显示信息。我需要在我的模板上获取此类信息:
['ChannelCategory_1: 'Channel_1', 'Channel_3'']
['ChannelCategory_2: 'Channel_2', 'Channel_4'']
我很乐意为您提供任何帮助,在此先感谢!
更新
为什么'QuerySet'对象没有'channels_list'属性?
tariff = Tariff.objects.prefetch_related('channels_list')
category_channel_dict = defaultdict(list)
for channel in tariff.channels_list.all():
category_channel_dict[channel.category.name].append(channel.name)
【问题讨论】:
标签: python-3.x django django-views many-to-many relationship