如何在不知道事先更新哪些字段的情况下更新django模型字段?

时间:2018-02-04 17:44:52

标签: python django django-models

我想在不知道事先更新哪些字段的情况下更新模型。 例如: 对我的网址api/user/(?P<pk>[0-9]+)/message-update/(?P<id>[0-9]+)/的请求将有一个有效负载JSON,其POST请求方法如下:

{
"category": "personal",
"type_of_transaction": "paid"
}

这里的问题是有效负载键值对将根据要更改的字段而不断变化。

我试过这个但似乎根本没有效果:

message = Message.objects.get(user=pk, id=id)
json_data = json.loads(request.body.decode(encoding='UTF-8'))
attributes_to_be_changed = json_data.keys()
values = json_data.values()
for i in attributes_to_be_changed:
    message.i = values[attributes_to_be_changed.index(i)]
message.save(update_fields=attributes_to_be_changed)
try:
    json_message = MessageSerializer(Message, many=False)
except Exception as e:
    return JsonResponse({"error": e})
return JsonResponse(json_message.data, safe=False)

我有一个消息模型如下:

user = models.ForeignKey(User, related_name='messages')
sender = models.CharField(max_length=15, blank=True)
body = models.CharField(max_length=400, blank=True)
account = models.ForeignKey(Account, blank=True, null=True)
card = models.ForeignKey(CreditCard, blank=True, null=True)
type_of_transaction = models.CharField(max_length=10)
message_date = models.DateTimeField(blank=True, null=True)
category = models.CharField(max_length=15, blank=True)
spent_at = models.CharField(max_length=15, blank=True)
meta = models.CharField(max_length=30, blank=True)
amount = models.FloatField()
lat = models.CharField(max_length=50, default="null")
lon = models.CharField(max_length=50, default="null")

def __str__(self):
    try:
        state = "Message from "+self.account.name+" for "+self.user.username
    except Exception:
        state = "Message from "+ self.card.card_number+"for"+self.user.username
    return state

我的序列化器:

class MessageSerializer(serializers.ModelSerializer):
    account = serializers.SerializerMethodField()

    def get_account(self, obj):
        try:
            name = obj.account.name
        except Exception:
            name = obj.card.card_number
        return name

    class Meta:
        model = Message
        fields = ('id','sender','body','account','category','spent_at','meta','type_of_transaction', 'amount', 'message_date')

3 个答案:

答案 0 :(得分:1)

嗯,我觉得你应该使用setattr

for key, value in json_data.items():
    setattr(message, key, value)

或者也许update_or_create也是个好主意 https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update-or-create

默认值是你的json_data

答案 1 :(得分:0)

您可以执行以下操作:

# Note: if id field is primary key, you don´t need to consult by user also

message_updated = Message.objects.filter(user=pk, id=id).update(**json_data)

答案 2 :(得分:0)

知道了! 这是json_message = MessageSerializer(Message, many=False)中的拼写错误。 将Message替换为message并使其正常运行。 它之前以模型为参数。