Django,ManyToMany字段

时间:2018-04-03 14:04:34

标签: django

我的博客应用中有两个型号:

class Tag(models.Model):
    tag_name = models.CharField(max_length=20,
                            null=True)

    def __str__(self):
        return self.tag_name

class Post(models.Model):
    tag = models.ManyToManyField(Tag, related_name="blog_tag",
                            blank=True)

在视图中我有:

tags = Tag.objects.all()

并且

post = get_object_or_404(Post,
                         status="published",
                         publish__year=year,
                         publish__month=month,
                         publish__day=day,
                         slug=post)

所以我的问题是 - 如何通过邮寄过滤标签?我的意思是我只想显示我添加到帖子中的标签。我尝试做的比在模板中做,但有些东西不起作用:

 {% for tag in tags %}
 {% if tag in post %}
   <div> 
     {{ tag.tag_name }}
   </div>
 {% endif %}
 {% endfor %}

发布模型:

class Post(models.Model):
    STATUS_CHOICES = (
        ("draft", "Draft"),
        ("published", "Published"),
        )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250,
                            unique_for_date="publish")
    author = models.ForeignKey(User,
                               related_name="blog_posts",
                               on_delete=models.CASCADE)
    tag = models.ManyToManyField(Tag, related_name="blog_tag",
                            blank=True)
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,
                              choices=STATUS_CHOICES,
                              default="draft")
    image = models.ImageField(upload_to="blog/%Y/%m/%d",
                              blank=True)

    class Meta:
        ordering = ("-publish",)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("blog:post_detail",
                       args=[self.publish.year,
                             self.publish.strftime("%m"),
                             self.publish.strftime("%d"),
                             self.slug])

答案是:

{% for tag in post.tag.all %}
    <div class="fa fa-plus-square">
     <a href="{% url "blog:post_list_by_tag" tag.id %}">{{ tag.tag_name }}</a>
     </div>
{% endfor %}

2 个答案:

答案 0 :(得分:1)

你可以这样做:

 {%for tag in tags %}
    {% if tag.id == post.tag.id%}
       <div> 
         {{ tag.tag_name }}
       </div>
    {%endif%}
 {%endfor%}

答案 1 :(得分:1)

由于您在ManyToManyField课程中使用了Post,如果该字段被称为tags而不是tag,则会更清楚,因为它指的是不止一件事。

class Post(models.Model):
    tags = models.ManyToManyField(Tag, related_name="blog_tag",
                            blank=True)

所以,一旦你查找了帖子:

post = get_object_or_404(Post,
                         status="published",
                         publish__year=year,
                         publish__month=month,
                         publish__day=day,
                         slug=post)

您将其传递给模板:

return render(request, 'post_detail.html', {'post': post})

然后在post_detail.html中,您可以呈现与帖子关联的标签:

{% for tag in post.tags.all %}
    <div> 
        {{ tag.tag_name }}
    </div>
{% endfor %}

无需明确过滤标记,因为ManyToManyField会为您处理。