0

I have a model as below:

class Person(models.Model): name = model.CharField(max_length = 255) mobile = model.IntegerField(null = True) city = model.CharField(max_length = 255) 

Now i need to create a model object using a json as below:

data = { "name" : "John", "age" : 31, "city" : "New York", "mobile" : 1234432156, "address" : "xyz" } 

In the above json, name, mobile, city are the fields in Person model. I have to create a model object using the above json. I have done like this:

Person.objects.create(**data) 

But it is throwing an error saying 'age' is invalid keyword argument for this function. My understanding is that, it is throwing error since there is no age field in the model.

How to create the model instance with such a json where all the keys are not the fields in the model.

3
  • But what are you expecting to happen with the age value? Why are you including it at all? Commented Nov 11, 2018 at 20:36
  • Thanks for your response. This is a sample question representing my problem. That json is not created by any one, it is generated from data base queries. In contrast, age might be not be used here, but it can be used in some other place. Commented Nov 11, 2018 at 20:42
  • 1
    This is not JSON, this is a Python dictionary. Commented Nov 11, 2018 at 20:48

1 Answer 1

1

Unless you know that your data is the same "shape" (i.e. has the same fields) as your model, you're going to be better off writing this out explicitly:

Person.objects.create(name=data['name'], mobile=data['mobile'], city=data['city']) 

(This is one of those explicit is better than implicit moments.)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your reply. I have done the same thing. I have written a function inside model and passed the data to that function. The function does the same thing you have done inside create

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.