gpt4 book ai didi

python - Django REST Framework 多对多创建和更新

转载 作者:行者123 更新时间:2023-12-01 09:30:11 25 4
gpt4 key购买 nike

模型.py:

class Book(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(max_length=500)
image = models.ImageField(height_field="height_field", width_field="width_field")
height_field = models.IntegerField(default=255)
width_field = models.IntegerField(default=255)
price = models.FloatField()
edition = models.CharField(max_length=100)
no_of_page = models.IntegerField()
country = models.CharField(max_length=50)
publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
authors = models.ManyToManyField(Author, through='AuthorBook')
ratings = GenericRelation(Rating, related_query_name='books')

class AuthorBook(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)

class Author(models.Model):
name = models.CharField(max_length=100)
biography = models.TextField(max_length=500)
image = models.ImageField(height_field="height_field", width_field="width_field")
height_field = models.IntegerField(default=255)
width_field = models.IntegerField(default=255)

序列化器.py

class AuthorListSerializer(ModelSerializer):
url = author_detail_url
class Meta:
model = Author
fields = [
'url',
'id',
'name',
]

class BookCreateUpdateSerializer(ModelSerializer):
authors = AuthorListSerializer(many=True, read_only=True)

def create(self, validated_data):
#code

def update(self, instance, validated_data):
#code

class Meta:
model = Book
fields = [
'name',
'description',
'price',
'edition',
'no_of_page',
'country',
'publication',
'authors',
]

View .py

class BookCreateAPIView(CreateAPIView):
queryset = Book.objects.all()
serializer_class = BookCreateUpdateSerializer

我正在致力于实现 Django REST Framework。我有两个模型 BookAuthor。但是 django create api view 不显示作者字段下拉列表。我检查了许多多对多领域的解决方案 DRF。请帮助我显示作者字段并编写 create()update 函数。如果你看到DRF api页面,就清楚了。

enter image description here

最佳答案

这是因为read_only=True 。尝试删除 bookserializer 的authors 字段的此参数:

class BookCreateUpdateSerializer(ModelSerializer):
authors = AuthorListSerializer(many=True)

关于python - Django REST Framework 多对多创建和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50035862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com