我有一个基本上连接两个不同用户的模型:
class Couple(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
user1 = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
blank=False,
related_name="user1"
)
user2 = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
blank=False,
related_name="user2"
)
def __str__(self):
return str(self.id)
接下来我做的是创建一个Serializer,其中user 1邀请user 2创建一对。我想通过编写user 2的电子邮件地址来实现这一点:
class CreateCoupleSerializer(serializers.Serializer):
partner_email = serializers.EmailField(write_only=True, max_length=250,
required=True)
def create(self, validated_data):
partner_email = validated_data['partner_email']
try:
partner = User.objects.get(email=partner_email)
except Exception:
partner = None
if not partner:
raise serializers.ValidationError(
{"details": 'User does not exist'})
if partner.couple_id:
raise serializers.ValidationError(
{"details": 'User is already assigned to a couple'})
user = self.context['request'].user
couple = Couple.objects.create(user1=user, user2=partner)
user.couple_id = couple.id
partner.couple_id = couple.id
user.save()
partner.save()
return couple
而这就是我的看法:
class CreateCoupleView(generics.CreateAPIView):
serializer_class = CreateCoupleSerializer
queryset = Couple.objects.all()
通过测试,我可以看到创建了Couple,这很好!但是,在我的身体React中,我得到了一个空的字典,而不是新的couple示例。
我的问题是为什么会这样
**附加问题:**什么时候应该在串行器端的def create()中创建逻辑,而不是在视图端的def create()中创建逻辑?
先谢谢你了。
1条答案
按热度按时间pb3skfrl1#
我通过将其替换为
serializers.ModelSerializer
并如下定义read_only_fields
来修复此问题: