且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 错误<模型>对象没有属性“更新"

更新时间:2023-12-01 21:40:40

这个错误的原因是.get()返回一个单独的对象,.update() 仅适用于查询集,例如使用 .filter() 而不是 .get() 返回的内容.

The reason for this error is that .get() returns an individual object and .update() only works on querysets, such as what would be returned with .filter() instead of .get().

如果您使用的是 .get(),那么 .update() 将不起作用.您需要手动将信息保存到对象中:

If you are using .get(), then .update() will not work. You will need to save the information to the object manually:

archivo = archivo.objects.get(archivo_id=procesar)
archivo.archivo_registros = sh.nrows
archivo.save()

您也可以使用 update_fields 如果您只想保存此特定数据:

You can also use update_fields if you only wish to save this particular piece of data:

archivo = archivo.objects.get(archivo_id=procesar)
archivo.archivo_registros = sh.nrows
archivo.save(update_fields=['archivo_registros'])

这可以防止触发您可能不想调用的任何信号.

This prevents triggering any signals that you may not want to invoke.

您的另一个选择是简单地使用 .filter().

Your other option is to simply use .filter().

archivo = archivo.objects.filter(archivo_id=procesar).update(archivo_registros=sh.nrows)

请注意,如果多个对象存在,这将更新它们.如果您想确保不会发生这种情况,您应该在过滤器中包含主键,或者使用较早的方法之一来确保您只修改单个对象.

Note that this will update multiple objects if they exist. If you want to be sure that doesn't happen, you should include the primary key in the filter, or use one of the earlier approaches to make sure you are only modifying a single object.