我希望得到所有与标签相关的帖子:
#models.py
class Post(models.Model):
tags = models.ManyToManyField('blogUserPlane.Tag')
title = models.CharField(max_length=200)
class Tag(models.Model):
name = models.CharField(max_length=200)
#views.py
def get_list_of_posts_by_tag_order_by_date(request):
# this works
list_of_posts = Post.objects.all().filter(tags__in=[1, 2])
# I want to use tags as name, not as id. Samething like this
# list_of_posts = Post.objects.all().filter(tags__in=["Tag1", "Tag2"])
html = ["title=%s<br> tags=%s<br>" % (p.title, p.tags.__dict__) for p in
list_of_posts] 返回HttpResponse(html)
第二个问题是过滤器返回错误的结果:
Post:
| id | title |
| 1 | post1 |
| 2 | post2 |
tags:
| id | post_id | tag_id |
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
Tag:
| id | name |
| 1 | Tag1 |
| 2 | Tag2 |
list_of_posts = Post.objects.all()。filter(tags__in = [1,2])返回: post1,post1,post2,但应该返回post1,post2