简体   繁体   English

如何通过 Django 中的用户模型引用模型?

[英]How do I reference a model via User model in Django?

So I have two models -- UserInfo model, which references Django's built-in User model, and Article model, written by each user, as below.所以我有两个模型—— UserInfo模型,它引用了 Django 的内置User模型,以及由每个用户编写的Article模型,如下所示。

class UserInfo(models.Model):
    objects = models.Manager()
    this_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, default=None)
    real_name = models.CharField(max_length=20, blank=False)

class Article(models.Model):
    objects = models.Manager()
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'article', null=True, default=None)
    body = models.CharField(max_length=20, blank=False)

And here's part of my views.py .这是我的views.py的一部分。

def create_ans_us(request):
    current_article = Article.objects.get(id=1)
    ...
    context = {
        'current_article' : current_article,
    }
    return render(request, 'main/main.html', context)

And in Django template tag, I'm trying to render the real_name field in UserInfo like below.在 Django 模板标签中,我试图在UserInfo呈现real_name字段,如下所示。

<html>
...
{{current_article.user_id.real_name}}
</html>

Now obviously, I want to render the real_name field to the template.现在很明显,我想将real_name字段呈现给模板。 How do I make this possible?我如何使这成为可能? Thanks in advance.提前致谢。 :) :)

You should follow the author of the current_article , so:您应该关注current_articleauthor ,因此:

{{ current_article.author.userinfo.real_name }}

This will result in an extra database call.这将导致额外的数据库调用。 You can obtain the data of the author in the same query where you fetch the object with .select_related(…) [Django-doc] :您可以在使用.select_related(…) [Django-doc]获取对象的同一查询中获取作者的数据:

from django.shortcuts import get_object_or_404

def create_ans_us(request):
    current_article = get_object_or_404(
        Article.objects.select_related('author', 'author__userinfo'),
        id=1
    )
    …
    context = {
        'current_article' : current_article,
    }
    return render(request, 'main/main.html', context)

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

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