24π
β
You could just do,
PartOne.objects.create(**json)
You can use the **kwargs syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function.
This is documented on section 4.7.4 of python tutorial., under unpacking argument lists.
Also, note that the same dict is not passed into the function. A new copy is created, so βjsonβ is not kwargs.
π€zaidfazil
3π
You may also want to take a look at modelform_factory
if you want to run more validation on your data or have more control over input. You can also do good stuff like attaching files.
from django.forms.models import modelform_factory
form = modelform_factory(PartOne, fields=('gender', 'gender_na', 'height', 'height_na',))
populated_form = form(data=my_json)
if populated_form.is_valid():
populated_form.save()
else:
# do something, maybe with populated_form.errors
π€whp
- Django β authentication, registration with email confirmation
- Add extra field to ModelForm
- How to profile django channels?
0π
There is another way I use, create a method in the model (serialize) and then use JsonResponse to return:
class User(AbstractUser):
u_username = models.CharField(max_length=100, default=None, blank=True, null=True)
p_pic = models.CharField(max_length=500, default=None, blank=True, null=True)
p_comment = models.CharField(max_length=200, default=None, blank=True, null=True)
def serializeProfile(self):
return {
"pk": self.pk,
"username": self.username,
"email": self.email
}
And then call the function, inside of the jsonRespone:
u_profile = User.objects.get(username='username')
JsonResponse(u_profile.serializeProfile())
The above worked for me.
π€thisispurecode
- How to store django objects as session variables ( object is not JSON serializable)?
- How to remove the language identifier from django-cms 2.4 URLs?
- How can my Model primary key start with a specific number?
- Stop nosetests from printing logging information?
- Annotate django query if filtered row exists in second table
Source:stackexchange.com