我創建Book
,Book_stat
它有關係與Django User
模型中Profile
模型的關係,我想顯示Book title
和full_name from Profile
默認STR返回字符串從Book_stat
Django的 - 從剖面模型返回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
由於它的工作,我有一個疑問,用戶是否有輪廓的實例或輪廓具有用戶實例,即'用戶.profile'或'profile.user'以及它們在我使用'OneToOneField'時如何相關? – Srinivas
取決於您如何訪問它,主要是從哪個模型中獲取值,請始終查找model-> field- > model-> field關係,它就是這樣 – Exprator