马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
我有个模型 , 其中 publish 及 author 都是外键。 class BooksModels(models.Model):
titile = models.CharField(verbose_name='书名', max_length=32, unique=True)
price = models.FloatField(verbose_name='价格', blank=True)
CATEGORY_CHOOSE = (
(1, '武侠小说'),
(2, '言情小说'),
(3, '修仙小说'),
(4, '都市小说'),
)
category = models.SmallIntegerField(verbose_name='类别', choices=CATEGORY_CHOOSE, default=1)
publish = models.ForeignKey(to='Publish', related_name='publish_books', on_delete=models.CASCADE)
author = models.ForeignKey(to='Author', related_name='author_books', on_delete=models.CASCADE)
class Meta:
db_table = 'Books'
另外还有一个 序列化器; 如果 没有自定义字段时, fields = '__all__'class BookSerializerEg(serializers.ModelSerializer):
#author_name = serializers.SerializerMethodField("get_author")
#publish_name = serializers.SerializerMethodField("get_publish")
def get_author(self, obj):
return obj.author.name
def get_publish(self, obj):
return obj.publish.name
class Meta:
model = models.BooksModels
fields = '__all__'
#fields = ['id', 'titile', 'price', 'category', 'author_name', 'publish_name']
通过post 方法 能成功 插入数据
插入的 json 为 {
"id":5,
"titile": "3小李飞刀",
"price": 78,
"category": 1,
"publish": 1,
"author": 1
}
# ****************************************
如果我的序列化器 添加上自定义字段时, 再插入数据,它就会死活报错,class BookSerializerEg(serializers.ModelSerializer):
author_name = serializers.SerializerMethodField("get_author")
publish_name = serializers.SerializerMethodField("get_publish")
def get_author(self, obj):
return obj.author.name
def get_publish(self, obj):
return obj.publish.name
class Meta:
model = models.BooksModels
#fields = '__all__'
fields = ['id', 'titile', 'price', 'category', 'author_name', 'publish_name']
报错信息如下:
IntegrityError at /api/v1/books/
NOT NULL constraint failed: Books.author_id
求解,在百度搜索了好久,也没有得到正解~~
|