显示引用表的列而不是django admin中的对象 [英] Show columns of referenced table instead of the object in django admin

查看:79
本文介绍了显示引用表的列而不是django admin中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何显示图书的 id title 列和 year 列,而不是 Books对象 >?

How can I show the columns id, title and the year of the book instead of "Books object"?

此屏幕快照显示了当前状态:

This screenshot shows the current state:

我的model.py看起来像这样:

My model.py looks like this:

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'

class AuthorsBooks我已将两个外键更改为OneToOneFields。

In the class AuthorsBooks I have changed the two foreign keys to OneToOneFields.

我的admin.py看起来像这样:

My admin.py looks like this:

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 __ 方法来使对象更具描述性。 (通常是大多数程序员这样做的方式)。

In your models.py file, you can use the special __str__ method in your concerned class to make your objects more descriptive. (This is generally the way most programmers do it)

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

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

You can choose any other attribute to make your object descriptive.

祝你好运!

这篇关于显示引用表的列而不是django admin中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆