如何与提供外键字段的外键一起创建多个对象?

时间:2018-08-16 11:20:31

标签: python django

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


class Lawyer(models.Model):

   user = models.OnetoOneField(User)

class Session(models.Model):

  lawyer = models.ForeignKey(Lawyer)

  name = models.TextField()


class SessionSerializer(serializers.ModelSerializer):

  email = serializers.EmailField()
  class Meta:
      model = Session
      fields=['name', 'lawyer','email']

请求中没有律师证,我的请求仅包含电子邮件和会话名称。

我需要使用会话序列化程序创建多个对象,但是如何通过使用传递的电子邮件来节省律师?

1 个答案:

答案 0 :(得分:3)

您需要做的就是创建Lawyer,还应该将laweyer字段的allow null设置为true。

class SessionSerializer(serializers.ModelSerializer):

  email = serializers.SerializerMethodField()
  lawyer = serializers.IntegerField(allow_null=True, required=False)

  fields=['name', 'lawyer','email']

  def create(self, validated_data):
     user = User.objects.create(email=validated_data.get('email'))
     lawyer = Lawyer.objects.create(user=user)
     name = validated_data.get('name')
     instance = Session.objects.create(lawyer=lawyer, name=name)
     return instance