繁体   English   中英

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

[英]Query column value of related object and store as variable

我试图在链接到我的Post模型的模型Category获取列name的值。 我想将name的值保存到变量中以备后用。 我尝试了print(post.categories.name)但是它返回值None 我可以通过运行post.categories.values()来确认是否存在实际值,该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)

你不能 您在Post模型post.categories categories定义为ManyToManyField ,因此post.categories是用于获取类别的ModelManager ,并且post.categories.all()返回与post相关的所有类别

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM