Consider these pseudo models:
class City(models.Model):
name = models.CharField()
region = models.ForeignKey(Region)
class Region(models.Model):
name = models.CharField()
country = models.ForeignKey(Country)
class Country(models.Model):
name = models.CharField()
and a form like this:
class MyForm(forms.Form):
city = forms.CharField()
region = forms.CharField()
country = models.CharField()
I would like my UpdateView to show the current values, so I have setup an initial like so:
model_initial = City.objects.filter(id=self.object.id).values()[0]
form = MyForm(initial=model_initial)
which is kinda stupid because self.object is already available so I could do the value mapping manually already
Anyway, this works but relationships aren’t captured, so I could do:
model_initial = City.objects.filter(id=self.object.id).values()[0]
model_initial.update({'region':Somequery, 'country':Somequery})
form = MyForm(initial=model_initial)
But that would pretty nasty and likely unneeded. I have tried to see what select_related hands me but calling values() on that query doenst return the extra fields.
so, Question: Whats a nice way to construct the initial dict in this case?
In Python, “nice” usually means “simple and readable”, so I’d personnaly gor for something like:
but a ModelForm might be a good solution too…