Search code examples
pythondjangodjango-rest-frameworkmany-to-many

Django REST Framework many to many create and update


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

I am working for implementing Django REST Framework. I have two models Book and Author. But django create api view don't show authors field drop down. I checked many solution DRF for many to many field. Please help me to show authors field and write create() and update function. If you see DRF api page, it will be clear.

enter image description here


Solution

  • This is because of read_only=True. Try to remove this argument for bookserializer's authors field:

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