无法在用于指定中介模型的ManyToManyField上设置值

时间:2018-11-19 09:20:51

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

如何为指定中介模型的ManyToManyField设置值?

在models.py

class BookUser(models.Model):
    email = models.EmailField()

class Book(models.Model):
    author_id= models.CharField(max_length=255)
    send_to = models.ManyToManyField(BookUser, through='BookUserRelationship')
    book_id = models.AutoField(primary_key=True)
    file_size = models.CharField(null=True)

class BookUserRelationship(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    user = models.ForeignKey(BookUser, on_delete=models.CASCADE)
    shared_date = models.DateTimeField(auto_now_add=True,null=True,blank=True)

试图在serializers.py中更新

class BookSerializer(serializers.ModelSerializer):
    send_to = BookUserSerializer(many=True, read_only=True)

    class Meta():
        model = Book
        fields = ('book_id', 'author_id','file_size','send_to')

class BookUserSerializer(serializers.ModelSerializer):
    model = BookUser
    fields = ('email')

在views.py中,通过将book_id作为查询参数传递来列出图书

class BookListView(generics.ListCreateAPIView):
    serializer_class = serializers.BookSerializer

    def get(self, request, *args, **kwargs):
        user = self.request.user
        book_id = self.request.query_params.get('book_id', None)
        if book_id:
            book = models.Book.objects.filter(book_id=book_id)
             return Response(serializers.BookSerializer(book[0]).data)

1 个答案:

答案 0 :(得分:0)

您根本不需要执行任何操作。通过创建BookUserRelationship实例,您已经在for循环中设置了相关数据。 多对多关系;您应该只删除instance.send_to.set(emails)行。