How to reference a Django model from another model

I need to create a view in the admin panel for a test program that writes books, publishers and authors (e.g. on djangoproject.com)

I have the following two models.

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

What I want to do is change the model of the book to reference the first_name of any authors and show it with 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',)

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

I tried a lot of different things, and he drove me crazy all day. Im pretty new for Python / Django.

Just to be clear - I just want the name of the author / author to appear next to the title of the book and the name of the publisher.

thank

+3
1

. Foreign Key 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.

+3

Source: https://habr.com/ru/post/1746099/


All Articles