[Solved]-How do I update an object's members using a dict?

20👍

You can use the setattr function to dynamically set attributes:

for key,value in request.GET.items():
    setattr(foo, key, value)

3👍

If request.GET is a dictionary and class Foo does not use __slots__, then this should also work:

# foo is a Foo instance
foo.__dict__.update(request.GET)
👤tzot

1👍

You’ve almost got it.

foo = Foo(**request.GET)

should do the trick.

1👍

If you are using this to create a model object that then gets persisted, I’d strongly recommend using a ModelForm. This would do what you described, in the canonical way for Django, with the addition of validation.

To expand — I didn’t mean to use it for form output, just form input. As follows:

class Foo(models.Model):
      a = models.CharField(max_length=255),
      b = models.PositiveIntegerField()

class FooForm(forms.ModelForm):
      class Meta:
          model = Foo

def insert_foo(request):
      form = FooForm(request.GET)
      if not form.is_valid():
          # Handle error conditions here
          pass
      else:
          form.save()

      return HttpResponse('Your response')

Then, assuming it’s bound to /import/, a GET to /import/?a=Test&b=1 would insert a new Foo with a = “Test” and b=”1″.

Leave a comment