models.py
from django.db import models
from django.contrib.auth.models import User
class Element(models.Model):
name = models.CharField(max_length=20)
class Group(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
elements = models.ManyToManyField(Element)
class Meta:
unique_together = ('user', 'name')
serializers.py
class ElementSerializer(serializers.HyperlinkedModelSerializer):
# group = serializers.ReadOnlyField(source='group.id')
class Meta:
model = Element
fields = ('name')
""" def save(self, group=None, *args, **kwargs):
if group is not None:
self.group = group
super(ElementSerializer, self).save(*args, **kwargs) """
class GroupSerializer(serializers.HyperlinkedModelSerializer):
elements = ElementSerializer(many=True)
class Meta:
model = Group
fields = ('url', 'name', 'elements')
views.py
class AddElement(APIView):
def get(self, request, pk, format=None):
serializer = ElementSerializer(context={'request': request})
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request, pk):
group = DBHandler.get_group_from_id(pk)
serializer = ElementSerializer(data=request.data, context={'request': request})
if not serializer.is_valid():
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
serializer.save()
# serializer.save(group = group)
return Response({}, status=status.HTTP_201_CREATED)
在我看来,我想从给定的数据创建一个元素,然后将此元素分配给现有的组。
我尝试将group作为序列化程序保存参数传递,并且它工作正常(注释代码),但我不知道接下来要去哪里。如何从ElementSerializer获取Element实例?或者还有另一种解决方法吗?