结合序列化器和模型功能

时间:2019-07-11 04:19:42

标签: python django django-allauth serializer django-rest-auth

我有两个序列化器... MyRegisterSerializer继承并扩展了流行的应用程序/程序包django-rest-auth,该程序/程序包连接到相当标准的用户表。我还为定制应用程序TeamSerializer(与用户一对多关系)提供了模型和序列化器。当用户注册时,我希望他们能够同时加入一个团队,因此我需要以某种方式创建一个团队,返回团队ID,然后将该ID传递给RegisterSerializer,以便团队可以存储在用户表中。我知道我可以打两次电话,首先创建团队并返回值,然后将其传递给寄存器序列化器,但是有没有办法在一个序列化器中完成所有这些工作?我是python的n00b使用者,考虑到我必须按原样返回get_cleaned_data()函数,因此找不到一个很好的例子。谢谢!

class TeamSerializer(serializers.ModelSerializer):

  class Meta:
    model = Team
    fields = ('id', 'name', 'logo', 'user')

class MyRegisterSerializer(RegisterSerializer):
  first_name = serializers.CharField()
  last_name = serializers.CharField()

  def get_cleaned_data(self):
    super(MyRegisterSerializer, self).get_cleaned_data()
    return {
        'team_id': <How do I get this value>
        'username': self.validated_data.get('username', ''),
        'position': self.validated_data.get('password1', ''),
        'email': self.validated_data.get('email', ''),
        'first_name': self.validated_data.get('first_name', ''),
        'last_name': self.validated_data.get('last_name', '')
    }

1 个答案:

答案 0 :(得分:4)

这取决于您要如何创建团队:

1。该团队是由其他一些信息创建的:

您应该可以使用此自定义字段:

from rest_framework.relations import PrimaryKeyRelatedField

class TeamPrimaryKeyRelatedField(PrimaryKeyRelatedField):
    def to_internal_value(self, data):
        if self.pk_field is not None:
            data = self.pk_field.to_internal_value(data)
        try:
            obj, created = self.get_queryset().get_or_create(
                pk=data,
                defaults=get_team_data(),
            )
            return obj
        except (TypeError, ValueError):
            self.fail('incorrect_type', data_type=type(data).__name__)

并在序列化器中使用它:

class MyRegisterSerializer(RegisterSerializer):
    team = TeamPrimaryKeyRelatedField()
    # ...

2。使用额外的用户输入来创建团队:

这似乎是writable nested serializers的完美用例:

class TeamSerializer(serializers.ModelSerializer):
    class Meta:
        model = Team
        fields = ('id', 'name', 'logo', 'user')

class MyRegisterSerializer(RegisterSerializer):
  first_name = serializers.CharField()
  last_name = serializers.CharField()
  team = TeamSerializer()

    def create(self, validated_data):
        team_data = validated_data.pop('team')
        # You could do this if the user is not necessary in the team object:
        team = Team.objects.create(**team_data)
        user = super().create(team=team, **validated_data)

        # Otherwise:
        user = super().create(**validated_data)
        # Should this be a many-to-many relationship?
        team = Team.objects.create(user=user, **team_data)
        # I don't know if this works/you need it:
        self.team = team
        # Or it should be like this?
        self.validated_data['team'] = team
        return user

我不确定您到底需要什么。让我知道您是否需要进一步的帮助。