标签和文章是多对多的关系
class Article(models.Model):
...
tag = models.ManyToManyField(Tag, related_name='tag', verbose_name='标签')
...
class Tag(models.Model):
"""
标签
"""
title = models.CharField(max_length=30, verbose_name='标签')
blog = models.ForeignKey(Blog, related_name='tag_blog', on_delete=models.CASCADE)
add_time = models.DateTimeField(default=datetime.now(), verbose_name='创建时间')
class Meta:
verbose_name_plural = '标签'
def __str__(self):
return self.title
视图中查询文章列表
# tag直接等于其id
article_list = Article.objects.filter(blog=blog, tag=int(val)).all()
class ArticleToTag(models.Model):
# to_field指定关联的主表的某个字段
tag = models.ForeignKey(to=Tag, verbose_name='文章', to_field='id')
article = models.ForeignKey(to=Article, verbose_name='标签', to_field='id')
class Meta:
# 联合唯一
unique_together = [
('tag', 'article')
]
在视图中查询文章列表
# 因为设置的是外键,所以使用tag_id
article_list = ArticleToTag.objects.filter(blog=blog, tag_id=int(val)).all()
for item in article_list:
print(item.article)
class Article(models.Model):
...
tag = models.ManyToManyField(
to='Tag',
through='ArticleToTag',
through_fields=('article', 'tag')
)
class Meta:
verbose_name_plural = '文章'