gpt4 book ai didi

django - 在 django admin 中显示引用表的列而不是对象

转载 作者:行者123 更新时间:2023-12-02 20:52:36 27 4
gpt4 key购买 nike

如何显示书籍的id标题年份列,而不是“Books对象>”?

此屏幕截图显示当前状态:

enter image description here

我的 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)

最佳答案

在 models.py 文件中,您可以在相关类中使用特殊的 __str__ 方法来使对象更具描述性。 (这通常是大多数程序员的做法)

def __str__(self):
return self.title #if your using 'title' as the attribute to identify your objects

您可以选择任何其他属性来使对象具有描述性。

祝你好运!

关于django - 在 django admin 中显示引用表的列而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com