首页 文章

如何从其他模型引用Django Model

提问于
浏览
3

我希望在管理面板中创建一个视图,用于记录书籍,出版商和作者的测试程序(如djangoproject.com)

我定义了以下两个模型 .

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

我想要做的是改变Book模型以引用任何作者的first_name并使用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',)

据我了解,你不能在同一个模型中有两个ForeignKeys . 谁能给我一个如何做到这一点的例子?

我尝试了许多不同的东西,它让我整天疯狂 . 我是Python / Django的新手 .

需要明确的是 - 我只是希望作者的名字和姓氏与书名和出版商名称一起出现 .

谢谢

1 回答

  • 3

    您可以在模型上拥有多个外键 . 如果要在 list_display 中放置外键字段的名称,您将始终只看到相关模型的 __unicode__ 表示 . 但是你可以在 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 .

相关问题