查询相关对象的列值并存储为变量

时间:2019-05-27 16:11:25

标签: python django

我正在尝试获取模型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)

1 个答案:

答案 0 :(得分:1)

不能。您在categories模型上将ManyToManyField定义为Post,因此post.categoriesModelManager来获取类别,并且post.categories.all()返回post关联的所有类别

您可以像这样获得帖子类别的名称列表:

category_names = [category.name for category in post.categories.all()]