我正在尝试创建Generic TemporalModelSerializer。
TemporalModelSerializer创建一条新记录并终止旧记录。
这样做是成功的,但是现在我想将串行器用于其他型号。
是否可以将模型传递给Serializer,然后在此行中使用它?
谢谢
OptionMaster.objects.filter(pk=instance.pk, vflag=1).update(**new_record)
浏览
class OptionMasterViewSet(viewsets.ModelViewSet):
serializer_class = TemporalModelSerializer
queryset = OptionMaster.objects.filter(vflag=1)
lookup_field = 'contractcode'
Generic TemporalModelSerializer
class TemporalModelSerializer(serializers.ModelSerializer):
vf = serializers.HiddenField(default=datetime.now())
vt = serializers.HiddenField(default=datetime(3000, 12, 31, 23, 00, 00, 000000))
vflag = serializers.HiddenField(default=1)
vu = serializers.HiddenField(default='Theodore')
class Meta:
model = OptionMaster
exclude = ('vt', 'vf', 'vu', 'vflag')
def update(self, instance, validated_data):
time_now = datetime.now()
old_record = {}
new_record = {}
for field in instance._meta.get_fields():
old_record[field.name] = getattr(instance, field.name)
new_record[field.name] = validated_data[field.name]
old_record['vt'] = time_now
old_record['vflag'] = 0
new_record['vf'] = time_now
self.delete_me(old_record)
OptionMaster.objects.filter(
pk=instance.pk, vflag=1).update(**new_record)
return instance
def delete_me(self, old_record):
obj = OptionMaster.objects.create(**old_record)
答案 0 :(得分:1)
这里的答案将有助于您如何设置serializer.py和views.py https://stackoverflow.com/a/30833834/4200352
然后在序列化程序中使用
self.Meta.model.objects.filter(pk=instance.pk, vflag=1).update(**new_record)