检查django模型中更改的字段值

时间:2016-08-04 15:39:33

标签: python django django-rest-framework

我使用django-rest-framework ModelSerializer解析来自restful API调用的数据。 这是代码:

    url = "API URL HERE"
    r = requests.get(url)
    json = r.json()
    serializer = myModelSerializer(data=json, many=True)
    if serializer.is_valid():
        serializer.save()

这是modelSerializer:

class myModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel

MYModel:

class MyModel(models.Model):
   City =  models.NullBooleanField(default=False, null=True)
   Status = models.CharField(max_length=100, null=True)
   stateName = models.CharField(max_length=50)
   marketingName = models.TextField(null=True)
   county = models.CharField(max_length=200, null=True)

我的问题是我需要找出上次调用restful api和更新数据时更改的字段值。或者如果有任何新记录。我如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

首先,您可以向updated = models.DateTimeField(auto_now=True) 添加一列:

save

每当更改实例时,都会更新。如果您在查询集中对此字段进行过滤,则可以确定更改了哪些行以及是否有新行。

找出哪些字段更改更难,但这是一个想法 - 在模型中添加字符串字段并为您的模型编写自定义class MyModel(models.Model): City = models.NullBooleanField(default=False, null=True) Status = models.CharField(max_length=100, null=True) stateName = models.CharField(max_length=50) marketingName = models.TextField(null=True) county = models.CharField(max_length=200, null=True) updated = models.DateTimeField(auto_now=True) updated_fields = models.CharField(max_length=200, null=True) def save(self, *args, **kwargs): if not self.pk: # if this is new, just save super(MyModel, self).save(*args, **kwargs) else: # get the original old = MyModel.objects.get(id=self.pk) # make a list of changed fields changed_fields = [] for field in self._meta.get_all_field_names(): if getattr(self, field, None) != getattr(old, field, None): if field not in ['updated', 'updated_fields']: changed_fields.append(old) # make a comma separated string self.updated_fields = ','.join(changed_fields) super(MyModel, self).save(*args, **kwargs) 方法,如下所示:

updated_fields

现在"query" : { "must" : { "term" : { "name" : "Jone Park" } } } 列将包含上次更新的字段集。