如何显示本书的 id , title 和年列而不是" Books对象"
此屏幕截图显示了当前状态:
我的model.py看起来像这样:
from __future__ import unicode_literals
from django.db import models
class Authors(models.Model):
name = models.CharField(max_length=45, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
class Meta:
managed = True
db_table = 'authors'
class AuthorsBooks(models.Model):
author_id = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author_id', primary_key=True)
book_id = models.OneToOneField('Books', models.DO_NOTHING, db_column='book_id', primary_key=True)
class Meta:
managed = True
db_table = 'authors_books'
unique_together = (('author_id', 'book_id'),)
class Awards(models.Model):
author = models.OneToOneField('Authors', models.DO_NOTHING, db_column='author', primary_key=True)
award_name = models.CharField(max_length=45)
year = models.IntegerField(blank=True, null=True)
class Meta:
managed = True
db_table = 'awards'
unique_together = (('author', 'award_name'),)
class Books(models.Model):
titel = models.CharField(max_length=45, blank=True, null=True)
year = models.IntegerField(blank=True, null=True)
class Meta:
managed = True
db_table = 'books'
在AuthorsBooks类中,我将两个外键更改为OneToOneFields。
我的admin.py看起来像这样:
from django.contrib import admin
from myapp.models import Authors
...
class AwardsInline(admin.TabularInline):
model = Awards
class AuthorsBooksInline(admin.TabularInline):
model = AuthorsBooks
class AuthorsAdmin(admin.ModelAdmin):
list_display = ("name", "birthday" )
inlines = (AwardsInline, AuthorsBooksInline)
admin.site.register(Authors, AuthorsAdmin)
答案 0 :(得分:1)
在models.py中为每个模型添加一个unicode函数。
class Authors(models.Model):
name = models.CharField(max_length=45, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
class Meta:
managed = True
db_table = 'authors'
def __unicode__(self):
return self.name
答案 1 :(得分:0)
在您的models.py文件中,您可以在所关注的类中使用特殊的__str__
方法来使您的对象更具描述性。 (通常这是大多数程序员这样做的方式)
def __str__(self):
return self.title #if your using 'title' as the attribute to identify your objects
您可以选择任何其他属性来使您的对象具有描述性。
祝你好运!
答案 2 :(得分:0)
Unicode对我不起作用,但是覆盖 str 可以有效