models.py
class Pallet_Mission(models.Model):
code = models.AutoField(primary_key=True)
load_type = models.CharField(max_length=20,null=True,blank=True)
mission_no = models.CharField(max_length=255, null=True,blank=True)
class PalletSubMission(models.Model):
mission_id = models.CharField(max_length=255,null=True,blank=True)
pallet_mission = models.ForeignKey(Pallet_Mission,on_delete=models.CASCADE,related_name='sub',null = True)
point = models.CharField(max_length=255,null=True,blank=True)
我有一个如下所示父模型和子模型,输出如下所示
"code": 52,
"mission_no": "test1234",
"load_type": "1234",
"sub": [
{
"id": 75,
"mission_id": "s1",
"point": null,
"pallet_mission": 52
},
{
"id": 76,
"mission_id": "s2",
"point": null,
"pallet_mission": 52
}
],
}
现在我的“使命”是手动插入的。我希望我的子模型的“mission_id”像自动增量一样显示“s1”为第一个数据“s2”为第二个数据等等。但它会在另一组数据中重置,如数据“code”:53“sub”中的第一个数据将再次以“s1”开始。不确定它是否是自动增量,我该怎么做?
serializers.py
class PalletSubSerializers(serializers.ModelSerializer):
id = serializers.IntegerField(required=False)
class Meta:
model = PalletSubMission
fields = '__all__'
class Pallet_Mission_Serializer(serializers.ModelSerializer):
sub = PalletSubSerializers(many=True)
class Meta:
model = Pallet_Mission
fields = '__all__'
def create(self, validated_data):
sub = validated_data.pop('sub')
mission = Pallet_Mission.objects.create(**validated_data)
for i in sub:
PalletSubMission.objects.create(pallet_mission=mission,**i)
return mission
def update(self,instance,validated_data):
sub =validated_data.pop('sub')
instance.load_type=validated_data.get('load_type',instance.load_type)
instance.mission_no=validated_data.get('mission_no',instance.mission_no)
instance.save()
sub_mission = PalletSubMission.objects.filter(pallet_mission=instance.pk).values_list('id', flat=True)
sub_mission_list =[]
for i in sub:
if "id" in i.keys():
if PalletSubMission.objects.filter(id=i['id']).exists():
sub_instance = PalletSubMission.objects.get(id=i['id'])
sub_instance.mission_id = i.get('mission_id',sub_instance.mission_id)
sub_instance.point = i.get('point',sub_instance.point)
sub_instance.save()
sub_mission_list.append(sub_instance.id)
else:
continue
else:
sub_instance = PalletSubMission.objects.create(pallet_mission=instance,**i)
sub_mission_list.append(sub_instance.id)
for i in sub_mission:
if i not in sub_mission_list:
PalletSubMission.objects.filter(pk=i).delete()
return instance
1条答案
按热度按时间5n0oy7gb1#
您可以使用如下重写
save()
方法来实现这些功能models.py
输出管理面板