class User(models.Model):
email = models.EmailField()
class Session(models.Model):
user = models.ForeignKey()
name = models.TextField()
class SessionSerializer(serializers.ModelSerializer):
email = serializers.SerializerMethodField()
fields=['name', 'email']
我需要使用会话序列化程序创建多个对象,但是如何通过使用传递的电子邮件保存用户?
答案 0 :(得分:1)
您可以使用SlugRelatedField
class SessionSerializer:
email = SlugRelatedField(source='user', slug_field='email', queryset=User.objects.all())
class Meta:
fields=['name', 'email']
请注意,email
模型的字段应该是唯一的:
class User(models.Model):
email = models.EmailField(unique=True)