我有这个模型:
文章:
class Article(models.Model):
sku = models.CharField(
max_length=5,
primary_key=True,
validators=[MinLengthValidator(5)]
)
ean = models.CharField(
max_length=13,
unique=True,
validators=[MinLengthValidator(13)]
)
parent = models.ForeignKey(
'Article',
related_name='children',
null=True,
blank=True,
on_delete=models.PROTECT
)
...
和ArticleTranslations
class ArticleTranslation(models.Model):
LANGUAGE_CHOICES = (
(settings.ENGLISH, _("english")),
(settings.FRENCH, _("french")),
(settings.GERMAN, _("german")),
(settings.ITALIAN, _("italian")),
(settings.PORTUGUESE, _("portuguese")),
(settings.SPANISH, _("spanish")),
)
article = models.ForeignKey(
'Article',
on_delete=models.CASCADE,
related_name='translations',
)
我需要同时返回两者,以在Django模板HTML中显示这两项。需要具有项和外键,并在相同的迭代中看到它。我想使用类List View和django的方法来做到这一点,而不是做不好的事情。 我有这个ListView:
def get_queryset(self):
queryset = (Article.objects
.all()
.prefetch_related('translations')
.order_by('-sku'))
print(queryset)
return queryset
在我的HTML中,需要显示外键值:
{% extends "base.html" %}
{% block content %}
{% for article in article_list %}
<div class="container">
<h2>{{ article.translations.NEED_TO_SHOW_THAT_PARAMETER }}</h2>
</div>
{% endfor %}
{% endblock content %}
答案 0 :(得分:1)
在您看来,您已经在获取正确的数据。因此,在模板中,您可以简单地遍历 await http.post("http://calikidsmap.com/test.php").then((response){
var ddd=jsonDecode(response.body);
Country_object_list = (ddd as List)
.map((data) => new country.fromJson(data))
.toList();
对象及其外键值(因为可以使用Article
来访问它们)
您正在使用related_name
,因此我认为您已在视图中设置了{% for article in article_list %}
。
我正在猜测您可能想要访问的context_object_name = 'article_list'
模型的额外字段。如果您的模型看起来像这样:
translations
然后可以在模板中执行以下操作:
class ArticleTranslation(models.Model):
LANGUAGE_CHOICES = (
(settings.ENGLISH, _("english")),
(settings.FRENCH, _("french")),
(settings.GERMAN, _("german")),
(settings.ITALIAN, _("italian")),
(settings.PORTUGUESE, _("portuguese")),
(settings.SPANISH, _("spanish")),
)
article = models.ForeignKey(
'Article',
on_delete=models.CASCADE,
related_name='translations',
)
language = models.CharField(max_length=10, choices=LANGUAGE_CHOICES)
说明:
{% extends "base.html" %}
{% block content %}
{% for article in article_list %}
<div class="container">
{% for object in article.translations.all %}
<h2>Chosend language - {{ object.language }}</h2>
{% endfor %}
</div>
{% endfor %}
{% endblock content %}
将为您提供一个article.translations.all
的所有翻译,使用此翻译您可以获取字段值