Aaron
Aaron

Reputation: 2475

Updating existing models with Django Rest Framework Serializers

I'm trying to update the a large list of models via a CSV that gets updated periodically. Right now the initial upload of the CSV works like a charm and all models are properly written to the DB. However, when I try to update the models after they've been created, my serializer.is_valid() returns the error ReturnDict([('inventory_number', [u'This field must be unique.'])]).

Thus my question is: How do I update a models I've already created via Serializers?

models.py:

class MyModel(models.Model):
    inventory_number = models.IntegerField(primary_key=True)
    location = models.CharField(max_length=40, blank=True)

views.py:

file_obj = request.data['file']

lines = csv.reader(file_obj, delimiter=",")
for line in lines:
    data = {
        'inventory_number': line[0],
        'location': line[1]
    }

    serializer = self.serializer_class(data=data)
    if serializer.is_valid():
        MyModel.objects.save_model(**serializer.validated_data)
    else:
        print serializer.errors

Lastly, I'm relatively new to Django and Django-Rest-Framework, so any insights/tips as to utilizing Serializers are appreciated. Thank you for your time.

Upvotes: 1

Views: 1605

Answers (1)

Yasel
Yasel

Reputation: 3120

First try to obtain an existing instance and update it if it exist, otherwise create it.
This post may be helpful
The solution looks something like this:

if serializer.is_valid():
        myinst, created = MyModel.objects.get_or_create(**serializer.validated_data)
        myinst.save()

You may want to make your method simpler:

for line in lines:
    myinst, created = MyModel.objects.get_or_create(inventory_number = line[0])
    myinst.location = line[1]
    myinst.save()

Upvotes: 1

Related Questions