Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更新django模型字段而不事先知道要更新哪些字段?_Python_Django_Django Models - Fatal编程技术网

Python 如何更新django模型字段而不事先知道要更新哪些字段?

Python 如何更新django模型字段而不事先知道要更新哪些字段?,python,django,django-models,Python,Django,Django Models,我想更新一个模型,而不需要事先知道要更新哪些字段。 例如: 对我的urlapi/user/(?P[0-9]+)/message update/(?P[0-9]+)/的请求将有一个负载JSON,其POST请求方法如下: { "category": "personal", "type_of_transaction": "paid" } 这里的问题是,有效负载键值对将根据要更改的字段而不断更改 我尝试过这个方法,但似乎没有任何效果: message = Message.objects.get(use

我想更新一个模型,而不需要事先知道要更新哪些字段。 例如: 对我的url
api/user/(?P[0-9]+)/message update/(?P[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')

嗯,我认为在你的情况下,你应该使用setattr

for key, value in json_data.items():
    setattr(message, key, value)
或者更新或者创建也可能是个好主意


默认值是json_数据

您可以执行以下操作:

# 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)
明白了! 这是在
json\u message=MessageSerializer(message,many=False)
中的一个输入错误。 将
消息
替换为
消息
,并使其正常工作。
它以前将模型作为参数。

尝试此操作后,我得到一个错误
int()参数必须是字符串或数字,而不是“DeferredAttribute”
。这是通过管理员检查后的完整回溯,我意识到消息已成功更改,然后我猜是序列化程序导致了错误。我正在添加序列化程序。它说
“Message”对象没有属性“update”
。仅供参考,我正在使用Django 1.11。竖起大拇指来修正主键对了,对不起。。。update方法仅适用于QuerySet对象。您可以更改.get to.filter方法或。。。(请稍候)请检查序列化程序编辑。我很确定这就是在成功保存消息时导致错误的原因。@Rahul您可以共享消息序列化程序代码吗?(您不应该控制该异常,因为它只能发生在编程错误中)