tluanga
tluanga

Reputation: 27

Updating the value of another model in Django Models

I cannot find a way to update the value of 'no' in Class A from Class B in Django Models

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

class B(models.Model):
   a = models.ForeignKey(A)
   def UpdateNo(self)
     #update no of class A

How to update 'no' field from

Upvotes: 1

Views: 2022

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477598

You can obtain the object with self.a, and then alter and save the object, like:

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

A ForeignKey will fetch lazily related objects, so self.a will contain the related A object. We thus then can handle it like we can handle any model object.

Upvotes: 5

Related Questions