创建新对象时Django Admin清除字段

时间:2017-01-08 00:05:09

标签: python django

我正在尝试编写BookApp。每当我创建一本新书时,它都会从选择中的前一本书中加载章节字段。如何删除关系但不删除内容。我还包括了照片。

#models.py
from django.db import models

class Category(models.Model):
  name = models.CharField(max_length=250)
  def __str__(self):
    return self.name

class Author(models.Model):
   name = models.CharField(max_length=250)
   def __str__(self):
      return self.name

class Chapter(models.Model):
   name = models.CharField(max_length=500)
   content = models.TextField()
   def __str__(self):
     return self.name


class Book(models.Model):
 category = models.ForeignKey(Category)
    name = models.CharField(max_length=500)
    summary = models.TextField()
    author = models.ForeignKey(Author)
    chapter = models.ForeignKey(Chapter)
    def __str__(self):
        return self.name`

在admin.py

from django.contrib import admin
from books.models import Category, Author, Chapter, Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('category', 'name', 'author', 'chapter')

admin.site.register(Category)
admin.site.register(Author)
admin.site.register(Chapter)
admin.site.register(Book, BookAdmin)

这里是问题的象征。 Added Book#1

Chapter of Book 1 still exist in loading

1 个答案:

答案 0 :(得分:1)

BookChapter之间存在外键关系:Chapter应该有Book的外键,而不是相反。