Django REST Framework可以创建和更新多对多

时间:2018-04-26 06:05:34

标签: python django django-rest-framework many-to-many

models.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)

serializers.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',
    ]

views.py

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

我正在努力实现Django REST Framework。我有两个模型BookAuthor。但是django创建api视图不显示作者字段下拉。我检查了许多解决方案DRF的许多领域。请帮我显示作者字段并编写create()update函数。如果您看到DRF api页面,则会很清楚。

enter image description here

1 个答案:

答案 0 :(得分:1)

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

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