更新Django模型中另一个模型的值

时间:2018-09-21 08:50:15

标签: django django-models

我找不到从Django模型中的类B更新类A中'no'值的方法

File -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors
File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors

如何从中更新“否”字段

1 个答案:

答案 0 :(得分:0)

您可以使用self.a获取对象,然后更改并保存该对象,例如:

class A(models.Model):
    no = models.IntegerField()

class B(models.Model):
    a = models.ForeignKey(A)

    def UpdateNo(self):
        my_a = self.a   # fetch the related A object in my_a
        my_a.no = 1234  # update the no field of that object
        my_a.save()     # save the update to the database

ForeignKey将延迟获取与 相关的对象,因此self.a将包含相关的A对象。这样我们就可以像处理任何模型对象一样处理它。