4

I'm wondering, what is a standard way of updating multiple fields which includes related fields of an instance of a model in django? ...

Class User(models.Model):
    id = models.CharField()
    name = models.CharField()
    dob = models.CharField()

Class Appointment(models.Model):
    user = models.ForeignKey(User)
    app_id = models.CharField()
    time = models.DateTimeField()
    status = models.CharField()

To update multiple fields in appointment model I could just do

dict ={
"app_id": "123",
"time": "2012-01-01 10:30",
"status": "Open"
}
Appointment.objects.filter(app_id=123).update(dict)

Is there a way to update the related model? How could I do an update on Appointment model and User Model?
Case:

dict ={
"name": "foo",
"app_id": "123",
"time": "2012-01-01 10:30",
"status": "Open"
}
Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
Joel James
  • 3,870
  • 9
  • 32
  • 47

1 Answers1

11

For clarity's sake - that's not what 'inherited' means. Appointment is related to user, but does not inherit from it.

The update method on the queryset can't do this in a single call. The docs say:

the only restriction on the QuerySet that is updated is that it can only update columns in the model’s main table, not on related models.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#update

If you have the app_id and nothing else, you can write a second update call:

User.objects.filter(appointment__app_id=123).update(name='foo')
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83