DRF多对多字段,创建,更新

1.models.py中
class Teams(models.Model):
   platformId = models.ManyToManyField(Platform, db_column="platformid", verbose_name=u"平台", help_text='平台',
                                       related_name="platformId", through='RelTeamsPlatform',
                                       through_fields=('teamId', 'platformId'))

class RelTeamsPlatform(models.Model):
   id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name=u'编号', help_text=u'编号')
   teamId = models.ForeignKey(Teams, db_column="teamid", help_text=u'team编号', verbose_name=u'team编号',
                              on_delete=models.SET_NULL, null=True, blank=True, related_name='RelTeamsPlatform_teamId')
   platformId = models.ForeignKey(Platform, db_column="platformid", help_text=u'编号', verbose_name=u'编号',
                                  on_delete=models.SET_NULL, null=True, blank=True,
                                  related_name='RelTeamsPlatform_platformId')

class Platform(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name=u'编号', help_text=u'编号')

2.serializers.py
class TeamsCreateSerializer(serializers.ModelSerializer):
   createTime = serializers.HiddenField(default=datetime.now)
   createUser = serializers.HiddenField(default=serializers.CurrentUserDefault())
   platformId =serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Platform.objects.all())

   class Meta:
       model = Teams
       exclude = ('modifyUser', 'modifyTime')

   def create(self, validated_data):
       tracks_data = validated_data.pop('platformId') #这里是先把Teams中的platformId
                                                      #这个多对多关系字段剔除出去
                                                      #tracks_data 就是被剔除出去的字段实例结果
       team = Teams.objects.create(**validated_data)  #到这里在创建一个teams实例
       for track_data in tracks_data:
           RelTeamsPlatform.objects.create(teamId=team, platformId=track_data,
                                           createUser=validated_data.get('createUser', None)) 
                                           #到这里是在中间表中把这个关系添加到关系表中
       return team

class TeamsUpdateSerializer(serializers.ModelSerializer):
   platformId = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Platform.objects.all())

   def update(self, instance, validated_data):
       serializers.raise_errors_on_nested_writes('update', self, validated_data)
       info = model_meta.get_field_info(instance)

       # list(instance.platformId.all()) 是修改前的数据,
       # validated_data['platformId'] 是修改后的数据,前后数据做对比,有改变往下面进行,
       # 没有该表就要
       if list(instance.platformId.all()) != validated_data['platformId']:  #
           tracks_data = validated_data.pop('platformId')
           RelTeamsPlatform.objects.filter(teamId=instance).delete()
           for track_data in tracks_data:
               RelTeamsPlatform.objects.create(teamId=instance, platformId=track_data,
                                               createUser=validated_data.get('modifyUser', None))
       else:
           tracks_data = validated_data.pop('platformId')
       for attr, value in validated_data.items():
           if attr in info.relations and info.relations[attr].to_many:
               field = getattr(instance, attr)
               field.set(value)
           else:
               setattr(instance, attr, value)
       instance.save()
       return instance


有人说更新的时候不用这样麻烦,但是作者尝试着做,没做到,希望有人知道,分享下



你可能感兴趣的:(DRF多对多字段,创建,更新)