2017-08-01 55 views
2

我創建BookBook_stat它有關係與Django User模型中Profile模型的關係,我想顯示Book titlefull_name from Profile默認STR返回字符串從Book_statDjango的 - 從剖面模型返回FULL_NAME具有與其他模型的Django用戶模型

models.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 

ADM in.py

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)  

,當我在我的Django管理頁面點擊Book_stat我想在我的Book_stat list

回答

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

顯示Book titleProfile full_name爲標題的嘗試這個希望你能得到它

+0

由於它的工作,我有一個疑問,用戶是否有輪廓的實例或輪廓具有用戶實例,即'用戶.profile'或'profile.user'以及它們在我使用'OneToOneField'時如何相關? – Srinivas

+0

取決於您如何訪問它,主要是從哪個模型中獲取值,請始終查找model-> field- > model-> field關係,它就是這樣 – Exprator

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 
1

試試這個:

在您的個人資料添加到模型related_name這樣的:

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

    def __str__(self): 
     return self.full_name 

而在你BookStat型號:

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