我正在尝试获取模型name
中与我的Category
模型链接的列Post
的值。我想将name
的值保存到变量中以备后用。我尝试了print(post.categories.name)
,但是它返回值None
。我可以通过运行post.categories.values()
并返回<QuerySet [{'id': 1, 'name': 'General'}]>
型号:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=30)
class Post(models.Model):
title = models.SlugField(max_length = 250, null = True, blank = True)
body = models.TextField()
created_on = models.DateTimeField(null=True)
last_modified = models.DateTimeField(null=True)
categories = models.ManyToManyField('Category', related_name='posts')
class Comment(models.Model):
author = models.CharField(max_length=60)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
观看次数:
def blog_detail(request, pk):
post = Post.objects.select_related().get(pk=pk)
category = post.categories.name # This returns None but should return General
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = Comment(
author=form.cleaned_data["author"],
body=form.cleaned_data["body"],
post=post
)
comment.save()
comments = Comment.objects.filter(post=post)
context = {
"post": post,
"comments": comments,
"form": form,
}
return render(request, "blog_detail.html", context)
答案 0 :(得分:1)
不能。您在categories
模型上将ManyToManyField
定义为Post
,因此post.categories
是ModelManager
来获取类别,并且post.categories.all()
返回与post
关联的所有类别。
您可以像这样获得帖子类别的名称列表:
category_names = [category.name for category in post.categories.all()]