I am writing a Django application and need to update a model with an AJAX request, which will only contain a subset of the model's fields as keys. So if I have the model
class TheModel(models.Model):
a = models.CharField(max_length=16)
b = models.IntegerField()
c = models.TextField()
d = models.ManyToManyField(AnotherModel)
then I could get requests like
id=7&a=Hello
id=7&a=Test&b=123
id=13&b=14&c=Description&d=6&d=10
that is, I will always get the ID field but any subset of the others.
I can't find a "nice" way to do this in Django 1.5: at first I tried
instance = get_instance_or_404(request["id"])
data = django.forms.models.model_to_dict(instance)
data.update(request.POST)
form = TheModelForm(data, instance=instance)
if form.is_valid():
form.save()
...
else:
...
but this doesn't seem to work well with the m2m field, and moreover model_to_dict feels incredibly ugly to me. So I also did
instance = get_instance_or_404(request["id"])
for k in TheModel._meta.fields:
if k in request:
setattr(instance, k, request[k])
try:
instance.full_clean()
except ValidationError as e:
...
instance.save()
but I don't exactly understand how to handle the m2m fields here either.
Is there an idiomatic way to do this in Django? Thanks in advance for your help.