如何在 Django 中过滤和显示'many to many'元素



我正在学习django,在我的项目中,我不知道如何在甲板详细信息页面上正确地获取和显示多对多关系中的元素。

型号.py

class Card(models.Model):
def upload_path(self, filename):
return os.path.join('cards/', filename)
image = models.ImageField(upload_to=upload_path)
card_num = models.CharField(max_length=20, default='')
name = models.CharField(max_length=500, default='')
desc = models.TextField(max_length=500, default='')
card_class = models.OneToOneField(CardClass, on_delete=models.DO_NOTHING, default='')
cost = models.OneToOneField(Cost, on_delete=models.DO_NOTHING, default='')
card_type = models.OneToOneField(CardType, on_delete=models.DO_NOTHING, default='')
rarity = models.OneToOneField(Rarity, on_delete=models.DO_NOTHING, default='')
resource = models.IntegerField(default=None)
attack = models.IntegerField(default=None)
defence = models.IntegerField(default=None)

def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('card:cardPageDetail', args=[self.name])

class Deck(models.Model):
def upload_path(self, filename):
return os.path.join('decks/', filename)
image = models.ImageField(upload_to=upload_path)
user = models.ForeignKey(User, on_delete=models.CASCADE)
cards_list = models.ManyToManyField(Card, related_name='cards_list')
deck_id = models.CharField(max_length=10, default='')
name = models.CharField(max_length=500, default='')
desc = models.CharField(max_length=500, default='')
price = models.CharField(max_length=500, default='')
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('card:deckPageDetail', args=[self.name])

视图.py

def deckPageDetail(request, name):
deck=get_object_or_404(Deck, name=name)
cards_all = Card.objects.all()
queryset = cards_all.objects.filter(cards_list__in=deck.deck_id)
print(queryset)
context = {
'deck': deck,
'cards_in_deck': queryset,
}
return render(request, 'landing/deck_detail.html', context)

我尝试了一些基于stackoverflow和谷歌叔叔的解决方案,但没有结果。我将感谢你的帮助。

您只需要访问牌组的card_list属性。

deck = Deck.objects.get(id=1)
for card in deck.cards_list.all():
print(card)

您已经拥有M2M的卡片组,因此您可以直接访问模板中的卡片列表。首先,让我们清理不需要的代码。

def deckPageDetail(request, name):
deck=get_object_or_404(Deck, name=name)
context = {
'deck': deck,
}
return render(request, 'landing/deck_detail.html', context)

然后在landing/deck_detail.html模板中,您可以使用下面的代码在卡片上循环。

{% for card in deck.cards_list.all %}
{{ card }}
{% endfor %}

如果你想访问卡片信息

{% for card in deck.cards_list.all %}
{{ card }} {{ card.image.url }} {{ card.card_num }}
{% endfor %}

以防你想把它放在视图中

def deckPageDetail(request, name):
deck=get_object_or_404(Deck, name=name)
queryset = deck.cards_list.all()
print(queryset)
context = {
'deck': deck,
'cards_in_deck': queryset,
}
return render(request, 'landing/deck_detail.html', context)

相关内容

  • 没有找到相关文章

最新更新