更新:
我正在尝试获取问题版本中属于部分的所有文章对象。即使在查看documentation django 2.x
之后,我也感到难过我可以获得所有版本的所有版本,但是我无法弄清楚如何获得与每个版本的版块相关的文章。
对于上下文,这是我在 django视图中的工作查询而没有获取文章:
def issue_edit_form(request, iid=0):
latest = utils.get_latest()
issue = Issue.objects.get(pk=iid)
editions = issue.edition_set.all()
sections = []
for i in editions:
sections.append(i.section_set.all().order_by("order"))
return render(request, 'issue_editor.html', {'latest': latest, 'issue': issue, 'editions': editions,
'sections': sections, 'article_form':
ArticleForm})
这是我的models.py
class Issue(models.Model):
volume = models.SmallIntegerField(default=0)
issue = models.SmallIntegerField(default=0)
issue_date = models.DateField()
published = models.BooleanField(default=False)
class Meta:
verbose_name = " Issue"
def __str__(self):
return "Vol. " + str(self.volume) + " Issue: " + str(self.issue) + ": " + str(self.issue_date)
class Edition(models.Model):
edition = models.CharField(max_length=100)
issue = models.ForeignKey(Issue, on_delete=models.CASCADE, null=True)
class Meta:
verbose_name = " Edition"
@property
def issue__name(self):
return self.issue.issue_date
def __str__(self):
return self.edition
class Section(models.Model):
section_name = models.CharField(max_length=100)
section_image = models.ImageField(blank=True, null=True)
order = models.SmallIntegerField(default=1)
section_hidden = models.BooleanField(default=False);
edition = models.ForeignKey(Edition, on_delete=models.CASCADE, null=True)
class Meta:
verbose_name = " Section"
def __str__(self):
return self.section_name
class Article(models.Model):
title = models.CharField(max_length=255)
article_url = models.URLField()
admin_description = models.CharField(max_length=255, blank=True)
# article_order = models.SmallIntegerField(default=1)
sections = models.ManyToManyField(Section, through="Placement")
class Meta:
verbose_name = "Article"
def __str__(self):
return self.title
class Placement(models.Model):
article = models.ForeignKey(Article, on_delete=models.DO_NOTHING, null=True)
section = models.ForeignKey(Section, on_delete=models.DO_NOTHING, null=True)
order = models.SmallIntegerField(default=1)
答案 0 :(得分:1)
因此,如果您想要每个部分的文章列表,您可以执行此操作
edition_sections = edition.section_set.all()
for section in edition_sections:
articles = section.articles_set.all()
或者,如果您不需要单独处理文章集,那么这也应该有效
edition_sections = edition.section_set.all()
articles = Article.objects.filter(sections__in=edition_sections)
这部分文档中有一些很好的例子 https://docs.djangoproject.com/en/2.0/topics/db/models/#intermediary-manytomany