Search code examples
djangodjango-modelsdjango-queryset

Reference Django Model Field from iterator in a for loop


I am attempting to create a model record using a for loop and cannot figure out how to reference the model field in a django create() function. I have mirrored response keys to the model fieldnames and want to loop through the response keys and assign the values in the model. Here is a simplified example.

r = requests.get(url)
r = r.json()

ModelOne.objects.create(
    for field in r:
        ModelOne.field = r[field]
)

I am trying to create the equivalent of

ModelOne.Objects.create(
    fieldone = r[fieldone]
    ,fieldtwo = r[fieldtwo]
)

Model:

class ModelOne(models.Model):
    fieldone = models.IntegerField(blank=True, null=True)
    fieldtwo = models.IntegerField(blank=True, null=True)

What I do not think works is trying to use .field in ModelOne.field as the object attribute. It doesn't return any errors but does not save the record either.

I have also tried using raw sql with the django connection library but run into many other hurdles with that method.

Is there a way to do this using the QuerySet API or should I be looking into another way?


Solution

  • You can "unpack" the dictionary, with:

    ModelOne.objects.create(**r)

    if r might contain other fields than fieldone and fieldtwo, you will need to filter these out, so:

    FIELDS = {'fieldone', 'fieldtwo'}
    ModelOne.objects.create(**{k: v for k, v in r.items() if k in FIELDS})