Django - 从Profile模型返回full_name,它与其他模型中的Django User模型有关

时间:2017-08-01 07:11:00

标签: django

我创建了BookBook_stat与[{1}}模型有关系的Profile模型,我正在尝试显示Django UserBook title默认 str full_name from Profile

返回字符串

models.py

Book_stat

admin.py

from django.db import models
from django.contrib.auth.models import User
from decimal import Decimal

# Create your models here.
class Book(models.Model):
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=150)

    def __str__(self):
        return self.full_name

class Book_stat(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    rating = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('0.00'))
    like = models.BooleanField(default=False)

    def __str__(self):
        return self.book.title # here i would like to return book title + full_name from Profile Model 

当我点击我的django管理页面中的from django.contrib import admin from .models import Book, Book_stat, Profile # Register your models here. admin.site.register(Book) admin.site.register(Book_stat) admin.site.register(Profile) 时,我想在Book_stat

中显示Book titleProfile full_name作为标题

3 个答案:

答案 0 :(得分:2)

    def __str__(self):
        return self.book.title +' '+ self.user.profile.full_name

试试这个希望你会得到它

答案 1 :(得分:1)

试试这个:

在您的个人资料模型中添加related_name,如下所示:

class Book_stat(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    rating = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal('0.00'))
    like = models.BooleanField(default=False)

    def __str__(self):
        return self.book.title + " - " + self.user.profile.full_name

在你的BookStat模型中:

           HC Reason Destination  freq       Perc
        <chr>  <chr>       <chr> <int>      <dbl>
 1    Germany  Study     Germany     9  0.3651116
 2    Germany   Work     Germany     3  0.1488095
 3    Germany Others     Germany     3  0.4901961
 4    Hungary  Study     Germany   105 21.4285714
 5    Hungary   Work     Germany   118 17.6382661
 6    Hungary Others     Germany    24  5.0955414
 7 Luxembourg  Study     Germany   362 31.5056571

答案 2 :(得分:0)

class Book_stat(models.Model):
    user = models.ForeignKey(User)
    book = models.ForeignKey(Book)
    rating = models.DecimalField(max_digits=5, decimal_places=2,     default=Decimal('0.00'))
    like = models.BooleanField(default=False)

    def __str__(self):
        return str(self.book.title) + " : " + str(self.user.get_full_name())  ## changes done here