MDN具有库数据库网页的django教程。 我正在尝试本节example,它确实有效。目的是当您看到每个作者时,您还可以在图书馆中看到他们的书籍清单。这是他们的github页面。我能够使作者页面列出他们各自的书。
现在,我想通过使作者页面也列出所有图书实例来进一步挑战自己。
因此,在以前,如果我去找JK Rowling这样的作者,我将能够看到Harry Potter 1、2和3(这是我添加到数据库中的三个)。现在,我要这样做,以便不仅可以看到这三本书,还可以看到这三本书的每个实例。因此,如果我有两本《哈利·波特1》,我将改为查看这2个条目。
这是我尝试过的事情。我添加了类BooksInstanceInLine,类似于我编写类BooksInline的方式,并且我还需要在books实例之间创建一个键。
在admin.py的AuthorAdmin类中,我添加了以下内容:
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
inlines = [BooksInstanceInline]
在models.py中的BookInstance类中,我添加了以下内容:
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
这是admin.py:
from django.contrib import admin
# Register your models here.
from catalog.models import Author, Genre, Book, BookInstance, Language
admin.site.register(Genre)
admin.site.register(Language)
class BooksInstanceInline(admin.TabularInline):
model = BookInstance
class BooksInline(admin.TabularInline):
model = Book
# Define the admin class
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
#inlines = [BooksInline]
inlines = [BooksInstanceInline]
# Register the admin class with the associated model
admin.site.register(Author, AuthorAdmin)
# Register the Admin classes for Book using the decorator
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'display_genre')
inlines = [BooksInstanceInline]
# Register the Admin classes for BookInstance using the decorator
@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
list_display = ('book', 'status', 'due_back', 'id')
list_filter = ('status', 'due_back')
fieldsets = (
(None, {
'fields': ('book', 'imprint', 'id')
}),
('Availability', {
'fields': ('status', 'due_back')
}),
)
这是我尝试添加密钥的models.py:
from django.db import models
# Create your models here.
class Genre(models.Model):
#FIELDS
name = models.CharField(max_length=200, help_text='Enter a book genra')
def __str__(self):
"""return representing the mymodelname object"""
return self.name
from django.urls import reverse # Used to generate URLs by reversing the URL patterns
class Book(models.Model):
"""Model representing a book (but not a specific copy of a book)."""
title = models.CharField(max_length=200)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
isbn = models.CharField('ISBN', max_length=13,
help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
# ManyToManyField used because genre can contain many books. Books can cover many genres.
# Genre class has already been defined so we can specify the object above.
genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
def __str__(self):
"""String for representing the Model object."""
return self.title
def get_absolute_url(self):
"""Returns the url to access a detail record for this book."""
return reverse('book-detail', args=[str(self.id)])
def display_genre(self):
"""Create a string for the Genre. This is required to display genre in Admin."""
return ', '.join(genre.name for genre in self.genre.all()[:3])
display_genre.short_description = 'Genre'
import uuid # Required for unique book instances
class BookInstance(models.Model):
"""Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
imprint = models.CharField('Imprint', max_length=200)
due_back = models.DateField(null=True, blank=True)
language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
LOAN_STATUS = (
('m', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(
max_length=1,
choices=LOAN_STATUS,
blank=True,
default='m',
help_text='Book availability',
)
class Meta:
ordering = ['due_back']
def __str__(self):
"""String for representing the Model object."""
return '{0} ({1})'.format(self.id,self.book.title)
class Author(models.Model):
"""Model representing an author."""
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField(null=True, blank=True)
class Meta:
ordering = ['last_name', 'first_name']
def get_absolute_url(self):
"""Returns the url to access a particular author instance."""
return reverse('author-detail', args=[str(self.id)])
def __str__(self):
"""String for representing the Model object."""
return '{0} ({1})'.format(self.last_name,self.first_name)
class Language(models.Model):
"""Model representing a Language (e.g. English, French, Japanese, etc.)"""
name = models.CharField(max_length=200, help_text="Enter the book's natural language (e.g. English, French, Japanese etc.)")
def __str__(self):
"""String for representing the Model object (in Admin site etc.)"""
return self.name
但是当我尝试它时,出现诸如this这样的操作错误:
有人知道这是为什么吗?