Home
» TechQns » How to initialise model objects explicitly without json data in django rest framework
How to initialise model objects explicitly without json data in django rest framework
May 4, 2014 | Posted by forumadmin under TechQns |
Comments off
|
This is my Model: Client
from django.db import models
class Client(models.Model):
client_code = models.CharField(max_length=20, blank=False)
client_name = models.CharField(max_length=50, blank=False)
debit = models.DecimalField(max_digits=19, decimal_places=2)
credit = models.DecimalField(max_digits=19, decimal_places=2)
This is a method in my views.py
def importClientsFromCSV(request):
if request.method == 'GET':
pathToCSV = os.path.dirname(os.path.abspath(__file__)) + '/portfolio.csv'
with open(pathToCSV, 'rU') as csvfile:
portfolioreader = csv.reader(csvfile, delimiter=',')
printer = "Number of Rows = "
rows = 0
for row in portfolioreader:
try:
client = Client.objects.get(client_code=row[0])
#Client Exists - Update Details
client.debit = row[2]
client.credit = row[3]
serializer = ClientSerializer(client)
if serializer.is_valid():
serializer.save()
rows = rows + 1
except Client.DoesNotExist:
client = Client()
client.client_code=row[0]
client.client_name=row[1]
client.debit=row[2]
client.credit=row[3]
serializer = ClientSerializer(client)
if serializer.is_valid():
serializer.save()
rows = rows + 1
if rows > 0:
return HttpResponse(pathToCSV+", "+printer+str(rows),status=200)
else:
return HttpResponse("Could Not Process",status=404)
The problem is I am facing is not able to add the client object that i create in Except block into my database. I am not sure why i am not able to serialize this object and save it.
![]() |
Asked By – Ishan Khanna | Read Answers |