如何从另一个模型引用Django模型 [英] How do I reference Django Model from another model

查看:244
本文介绍了如何从另一个模型引用Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在管理面板中创建一个用于记录图书,发布商和作者的测试程序(如在djangoproject.com上)

Im looking to create a view in the admin panel for a test program which logs Books, publishers and authors (as on djangoproject.com)

我有以下内容定义了两个模型。

I have the following two models defined.

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()

    def __unicode__(self):
        return self.title

我想做什么,是改变书模型来引用任何作者的first_name,并使用管理员显示.AdminModels。

What I want to do, is change the Book model to reference the first_name of any authors and show this using admin.AdminModels.

#Here is the admin model I've created.

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'publisher', 'publication_date') # Author would in here
    list_filter = ('publication_date',)
    date_hierarchy = 'publication_date'
    ordering = ('-publication_date',)
    fields = ('title', 'authors', 'publisher', 'publication_date')
    filter_horizontal = ('authors',)
    raw_id_fields = ('publisher',)

据了解,您不能在同一模型中拥有两个ForeignKey。任何人都可以给我一个如何做到这一点的例子?

As I understand it, you cannot have two ForeignKeys in the same model. Can anyone give me an example of how to do this?

我已经尝试了不同的东西,它一直驱使我疯狂。我相当新的Python / Django。

I've tried loads of different things and its been driving me mad all day. Im pretty new to Python/Django.

只是为了清楚 - 我只是喜欢作者的姓/名与书名和发行者一起出现名称。

Just to be clear - I'd simply like the Author(s) First/Last name to appear alongside the book title and publisher name.

谢谢

推荐答案

您可以有多个外键一个模型。
如果你把一个外键字段的名字放在 list_display 中,你总是会看到 __ unicode __ 的相关模型。
但是您可以添加一个这样的函数到您的 BookAdmin

You can have more than one Foreign Key on a model. If you would put a Foreign-Key field's name in list_display you will always just see the __unicode__ representation of the associated model. But you can add a function like this to your BookAdmin:

def first_names(self, obj):
    return ','.join(a.first_name for a in obj.authors.all())
get_sites.short_description = 'First Names'

然后将'first_names'添加到 list_display

这篇关于如何从另一个模型引用Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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