I would like to know how to modify the way I represent the JSON Response of my requests to the API created with DRF, tabs, spaces, etc..., in order to respond exactly to my frontend app.
I have the following code:
My models.py extract:
class Email(models.Model):
user_email = models.CharField(primary_key=True, max_length=200)
user_phone_number = models.IntegerField()
user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '')
lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
user_address = models.CharField(max_length=200)
creation_date = models.DateTimeField(default=None)
email_status = models.BooleanField(default=False)
email_score = models.IntegerField()
valid_email = models.BooleanField(default=False)
fraud = models.BooleanField(default=False)
My views.py extract:
class UserListView(APIView):
serializer_class = EmailSerializer
queryset = Email.objects.all()
pagination_class = StandardResultsSetPagination
def get_serializer_class(self):
if self.action == 'list':
return EmailListSerializer
return EmailSerializer
def post(self, request, *args, **kwargs):
parametros = request.POST
email='email=' + request._full_data['user_email']
response = UserConnector(email).get_user_data()
obgs = response[1]['results']
if len(obgs) == 0:
user_email = self.request.POST.get('user_email')
email_stat = ''
email_scor = ''
email_valid = ''
frau = ''
else:
obg = response[1]['results'][0]
user_email = self.request.POST.get('user_email')
email_stat = obg.get('email_status')
email_scor = obg.get('email_score')
email_valid = obg.get('valid_email')
frau = obg.get('fraud')
NewEmail = Email(
user_email = user_email,
user_phone_number = self.request.POST.get('user_phone_number'),
user_device_id = request.META.get('HTTP_DEVICE', ''),
lat = self.request.POST.get('lat'),
lng = self.request.POST.get('lng'),
user_address = self.request.POST.get('user_address'),
creation_date = timezone.now,
email_status = email_stat,
email_score = email_scor,
valid_email = email_valid,
fraud = frau
)
NewEmail.save()
serializer = EmailSerializer(NewEmail)
return Response(serializer.data)
I have receive the folowing JSON response:
{
"user_email": "meloadik#gmail.com",
"user_phone_number": 8117904544,
"user_device_id": "",
"lat": "20.9750000000000000",
"lng": "89.6141400000000000",
"user_address": "rfm mz5 lt4",
"creation_date": "2022-08-23T22:47:13.687178Z",
"email_status": null,
"email_score": 0,
"valid_email": 0,
"fraud": 0
}
I want to know how to format the JSON response differently, like this:
{
"email_response": {
"user_email": "carl#trully.ai",
"creation_date": "2020/06/01",
"email_status": "active",
"email_score": 910,
"valid_email": 1,
"fraud": 0
},
"phone_response": {
"user_phone_number": 8117904544,
}
}
Or modify my JSON Response with different types of styles, tabs, spaces, etc...
A quick fix would be to override EmailSerializer's to_representation method to something like this (pseudocode):
def to_representation(self, instance):
representation = super(EmailSerializer, self).to_representation(instance)
new_representation = {}
new_representation['email_response'] = {field: representation.get(field) for field in email_fields}
new_representation['phone_response'] = {field: representation.get(field) for field in phone_fields}
return new_representation
Related
views.py
#api_view(["POST", "GET"])
#permission_classes([IsAuthenticated])
def add_order(request, pk):
print(request.user)
customer = md.Customer.objects.get(pk=pk)
if request.method == "POST":
description = request.data['description']
price = request.data['price']
order = md.Order.objects.create(customer=customer,
date_created=zt.now(),
description=description,
price=float(price),
customer_total_when_created=customer.total_owe[0]
)
try:
is_paid = request.data['is_paid']
if is_paid == "on":
who_paid = request.data['who_paid']
payment_method = request.data['payment_method']
who_took_money = request.user
if who_paid == customer.name:
order.who_paid = customer
elif who_paid == customer.parent:
order.who_paid = customer.parent
order.payment_method = payment_method
order.who_took_money = who_took_money
order.date_paid = zt.now()
customer.total = customer.total_owe
customer.save()
order.save()
except:
print("no payment succeed")
order_api = OrderSerializer(order)
return Response(order_api.data)
customer_api = CustomerSerializer(customer)
parent_api = CustomerSerializer(customer.parent)
context = {
"customer": customer_api.data,
"parent":parent_api.data,
"sample": [
{"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"}
]
}
return Response(context)
models.py
class Order(models.Model):
payment_method_list = [("CASH","CASH"),("CARD","CARD")]
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,)
who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created')
who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money')
payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True)
date_paid = models.DateTimeField(blank=True,null=True)
date_created = models.DateTimeField(blank=True, null=True)
date_modified = models.DateTimeField(blank=True, null=True, auto_now=True)
is_paid = models.BooleanField(default=False, blank=True,null=True)
customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
description = models.TextField(blank=True,null=True)
price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
def __str__(self):
return self.description[0:12]
from django.db.models.signals import post_save
def update_total_owe_created_order(sender,instance,created,**kwargs):
if created:
order = instance
customer = order.customer
customer.total = customer.total_owe[0]
customer.save()
post_save.connect(update_total_owe_created_order,sender=Order)
def update_total_owe_updated_order(sender,instance,created,**kwargs):
if created==False:
order = instance
customer = order.customer
customer.total = customer.total_owe[0]
customer.save()
post_save.connect(update_total_owe_updated_order,sender=Order)
I have an app that you send your order to and it adds to database.
It only allows authenticated user to add order; so it shows who added that order. I can get the request.user with JWT authentication but can't save the model. When I send an API post request, I get that error. I could get the user with token but it gives me that error. I don't know why. I am using postman. I didn't get it normally but when I use postman it doesn't work.
ret = super().data
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\fields.py", line 1127, in to_representation
value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
The price in your Order model is a decimal field but you are casting the price from post request to float while creating the Order object.
price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
The price should be a Decimal object instead of float.
order = md.Order.objects.create(customer=customer,
date_created=zt.now(),
description=description,
price=Decimal(price),
customer_total_when_created=customer.total_owe[0]
)
customer_total_when_created should also be a Decimal instance but you haven't posted the Customer model which has total_owe.
I am working with django viewsets and i want an extra field from the request for validation.
What i want is the extra field role_id which should be coming from the request. The role id if passed, i should convert the employee to user and assign the role_id to the user.
Even though i am sending the role_id from request but i am unable to get it in the create or update method. Can someone please help me to know how can i fetch extra field from response
serializer.py
class EmployeeModelSerializer(serializers.ModelSerializer):
"""Employee model serializer"""
address = EmployeeAddressModelSerializer(required=False)
detail = EmployeeDetailModelSerializer(required=False)
demographic = EmployeeDemographicModelSerializer(required=False)
contact = EmployeeContactModelSerializer(required=False)
nok = EmployeeNokModelSerializer(required=False)
visa = EmployeeVisaModelSerializer(required=False)
dbs = EmployeeDBSModelSerializer(required=False)
job_detail = EmployeeJobDetailModelSerializer(required=False)
preference = EmployeePreferenceModelSerializer(required=False)
skills = EmployeeSkillsModelSerializer(many=True, read_only=True)
user = UserModelSerializer(required=False)
serializersMap = {
"address": EmployeeAddressModelSerializer,
"detail": EmployeeDetailModelSerializer,
"demographic": EmployeeDemographicModelSerializer,
"contact": EmployeeContactModelSerializer,
"nok": EmployeeNokModelSerializer,
"visa": EmployeeVisaModelSerializer,
"dbs": EmployeeDBSModelSerializer,
"job_detail": EmployeeJobDetailModelSerializer,
"preference": EmployeePreferenceModelSerializer,
"user": UserModelSerializer,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.context["gender"] = None
self.context["title"] = None
self.context["marital_status"] = None
self.context["employee_status"] = None
def internal_validate(self, data, field):
self.context[field] = data
if data == None:
return data
elif data.id:
return data.id
return data
def validate_gender(self, data):
return self.internal_validate(data, "gender")
def validate_title(self, data):
return self.internal_validate(data, "title")
def validate_marital_status(self, data):
return self.internal_validate(data, "marital_status")
def validate_employee_status(self, data):
return self.internal_validate(data, "employee_status")
user = serializers.SlugRelatedField(
read_only=True,
slug_field='username'
)
class Meta:
"""Meta class."""
model = Employee
fields = '__all__'
def get_fullname(self, obj):
return obj.first_name + " " + obj.last_name
def create(self, data):
data["address"] = self.saveForeign(data, "address")
data["detail"] = self.saveForeign(data, "detail")
data["demographic"] = self.saveForeign(data, "demographic")
data["contact"] = self.saveForeign(data, "contact")
data["nok"] = self.saveForeign(data, "nok")
data["visa"] = self.saveForeign(data, "visa")
data["dbs"] = self.saveForeign(data, "dbs")
data["job_detail"] = self.saveForeign(data, "job_detail")
data["preference"] = self.saveForeign(data, "preference")
data.pop("skills", None)
self.setContext(data)
employee = Employee.objects.create(**data)
return employee
def update(self, instance, data):
instance.address = self.updateForeign(instance.address, data, "address")
instance.detail = self.updateForeign(instance.detail, data, "detail")
instance.demographic = self.updateForeign(instance.demographic, data, "demographic")
instance.contact = self.updateForeign(instance.contact, data, "contact")
instance.nok = self.updateForeign(instance.nok, data, "nok")
instance.visa = self.updateForeign(instance.visa, data, "visa")
instance.dbs = self.updateForeign(instance.dbs, data, "dbs")
instance.job_detail = self.updateForeign(instance.job_detail, data, "job_detail")
instance.preference = self.updateForeign(instance.preference, data, "preference")
self.setContext(data)
return super(EmployeeModelSerializer, self).update(instance, data)
def saveForeign(self, data, name):
field = data.get(name)
data.pop(name, None)
if field is None:
return None
serializer = self.serializersMap.get(name)(data=field)
if serializer.is_valid(raise_exception=True):
return serializer.save()
def updateForeign(self, instance, data, name):
field = data.get(name)
data.pop(name, None)
if field is None:
return None
if not instance:
serializer = self.serializersMap.get(name)(data=field, context={})
if serializer.is_valid(raise_exception=True):
return serializer.save()
else:
serializer = self.serializersMap.get(name)(instance, data=field, context={})
if serializer.is_valid(raise_exception=True):
return serializer.update(instance, field)
def setContext(self, data):
if self.context["gender"] != None:
data["gender"] = self.context['gender']
if self.context["title"] != None:
data["title"] = self.context['title']
if self.context["marital_status"] != None:
data["marital_status"] = self.context['marital_status']
if self.context["employee_status"] != None:
data["employee_status"] = self.context['employee_status']
views.py
"""Employee view set"""
# authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = Employee.objects.filter(is_active=True).order_by('-modified')
serializer_class = EmployeeModelSerializer
filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend)
filter_fields = [
"job_detail__employment_type_id",
"job_detail__employee_category_id",
"job_detail__job_title_id",
"skills__name__id"
]
ordering_fields = [
'modified',
'job_detail__branch__name',
'full_name',
'reference',
'employee_status__name',
'address__name'
]
search_fields = [
'full_name',
'last_name',
'address__zip_code',
'contact__mobile_number'
]
def destroy(self, request, pk=None):
employee = self.get_object()
employee.is_active = False
employee.save()
return Response({'message': 'deleted!'}, status=status.HTTP_200_OK)
models.py
class Employee(Person):
user = models.ForeignKey(
'users.User',
null=True,
on_delete=models.SET_NULL
)
employee_status = models.ForeignKey(
'core.Employee_Status',
null=True,
blank=True,
on_delete=models.SET_NULL
)
title = models.ForeignKey(
'core.Title',
null=True,
blank=True,
on_delete=models.SET_NULL
)
payroll_ref = models.CharField(
'Payroll -Reference',
max_length=25,
blank=True,
default=''
)
address = models.OneToOneField(
'employees.Employee_Address',
null=True,
on_delete=models.SET_NULL
)
contact = models.OneToOneField(
'employees.Employee_Contact',
null=True,
on_delete=models.SET_NULL
)
dbs = models.OneToOneField(
'employees.Employee_dbs',
null=True,
on_delete=models.SET_NULL
)
demographic = models.OneToOneField(
'employees.Employee_Demographic',
null=True,
on_delete=models.SET_NULL
)
detail = models.OneToOneField(
'employees.Employee_Detail',
null=True,
on_delete=models.SET_NULL
)
job_detail = models.OneToOneField(
'employees.Employee_Job_Detail',
null=True,
on_delete=models.SET_NULL
)
nok = models.OneToOneField(
'employees.Employee_NOK',
null=True,
on_delete=models.SET_NULL
)
preference = models.OneToOneField(
'employees.Employee_Preference',
null=True,
on_delete=models.SET_NULL
)
visa = models.OneToOneField(
'employees.Employee_Visa',
null=True,
on_delete=models.SET_NULL
)
skills = models.ManyToManyField(
'employees.Employee_Skill',
related_name='Employee',
)
class Meta:
verbose_name = 'Employee - Basic Info'
verbose_name_plural = 'Employees - Basic Info'
request parameter
{
"first_name": "first name",
"last_name": "last name",
"date_of_birth": "2017-02-12",
"is_active": true,
"role_id": "role_id_goes_here",
"address": {
"name": "address name",
"line_1": "line 1",
"city": "city",
"state": "state",
"country": "country",
"zip_code": "zip code"
},
"nok": {
"no": "123sad",
"full_name": "full name nok",
"mobile": 123456789,
"email": "jesus#iconos.mx",
"title": null
},
"title": null
}
This is my model file which has the owner field name
class PotholeImages(models.Model):
"""Upload images with details """
image = models.ImageField(
upload_to='photos/%Y/%m/%d',
)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
default = 'unknown',
)
state_name = models.CharField(
blank = False,
max_length = 30,
default = 'unknown',
)
country_name = models.CharField(
blank = False,
max_length = 30,
default = 'unknown',
)
name = models.CharField(default=uuid.uuid4, max_length=40)
cordinate_X = models.DecimalField(max_digits=22, decimal_places=16)
cordinate_Y = models.DecimalField(max_digits=22, decimal_places=16)
created_date = models.DateTimeField(auto_now_add=True)
road_name = models.CharField(max_length = 100, default = 'unknown')
def __str__(self):
return self.name
Serializer file
class ImageSerializer(serializers.ModelSerializer):
"""Uploading Pothoele Images"""
class Meta:
model = PotholeImages
fields = ('image','state_name',
'country_name','cordinate_X',
'cordinate_Y','road_name',)
def to_representation(self, instance):
rep = super(ImageSerializer, self).to_representation(instance)
rep['owner'] = instance.owner.username
# print(rep)
return rep
views file
class ImageViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
queryset = PotholeImages.objects.all()
serializer_class = serializers.ImageSerializer
def perform_create(self, serializer):
print(self.request.user)
serializer.save(user=self.request.user)
I want whenever a person sends a post request on
http://127.0.0.1:8000/images_api/imageView/
Then from the token, username gets detected and it should be passed in the owner field name.
Could anyone please help
Thanks
Finally, I have found the answer I have made through APIView
class ImageAPIView(APIView):
authentication_classes = (TokenAuthentication,)
def post(self, request):
## username
user = request.user
is_tokened = Token.objects.filter(user = user)
print("user name is ", user)
data = request.data
data['owner'] = user.id
serializer = serializers.ImageSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=200)
ResponseData = "{} image sent by user".format(user.id)
return Response(ResponseData, status=status.HTTP_200_OK)
I have problem with rest_framework.viewsets.ReadOnlyModelViewSet.
class ProductFilter(filters.FilterSet):
meat_type = filters.CharFilter(lookup_expr='slug__iexact')
category = filters.CharFilter(lookup_expr='slug__iexact')
class Meta:
model = Product
fields = {
'price': ['gte', 'lte'],
}
ordering_fields = ['price', ]
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filterset_class = ProductFilter
#action(methods=['get'], detail=False)
def get_products(self, request):
products = self.get_queryset().order_by('-created')
serializer = self.get_serializer_class()(products, many=True)
print('SHOW IT')
if len(products) == 0:
return Response(status=status.HTTP_204_NO_CONTENT)
return Response(serializer.data, status=status.HTTP_200_OK)
My problem is that print in get_products not work, but code give good result with filters objects. My urls:
router = routers.DefaultRouter()
router.register('', views.ProductViewSet)
urlpatterns = [
path('shop/', include(router.urls))
]
Tests:
class TestViews(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/shop/"
self.search_url = "/api/shop/?price__lte={}&price__gte={}&meat_type={}&category={}"
self.category1 = Category.objects.create(name='cattest1',
slug='cattest1')
self.category2 = Category.objects.create(name='cattest2',
slug='cattest2')
self.meat_type1 = MeatType.objects.create(name='meattest1',
slug='meattest1')
self.meat_type2 = MeatType.objects.create(name='meattest2',
slug='meattest2')
self.product1 = Product.objects.create(category=self.category1,
meat_type=self.meat_type2,
name='prodtest1',
slug='prodtest1',
price=50)
self.product2 = Product.objects.create(category=self.category1,
meat_type=self.meat_type1,
name='prodtest2',
slug='prodtest2',
price=75)
self.product3 = Product.objects.create(category=self.category2,
meat_type=self.meat_type2,
name='prodtest3',
slug='prodtest3',
price=20)
self.product4 = Product.objects.create(category=self.category2,
meat_type=self.meat_type1,
name='prodtest4',
slug='prodtest4',
price=150)
def test_get_products_all(self):
response = self.client.get(self.url)
self.assertEqual(200, response.status_code)
self.assertEqual(4, len(response.data))
def test_get_products_no_content(self):
Product.objects.all().delete()
response = self.client.get(self.url)
self.assertEqual(204, response.status_code)
def test_product_greater_than(self):
response = self.client.get(self.search_url.format(
"", "55", "", ""
))
self.assertEqual(200, response.status_code)
self.assertEqual(2, len(response.data))
Test test_get_products_no_content fail with error:
assertionError: 204 != 200.
Somebody have any idea?
Thanks for any answer
Magnus
EDIT
Created this function, is pass good data to filter.
DICT {'price__lte': '50', 'price__gte': '100', 'meat_type': 'wieprzowina'}
But I have problem when I put it as filter argument. Got error:
invalid literal for int() with base 10: 'wieprzowina'. It try to change string to number, but I dont know why.
def get_queryset(self):
filter_params = self.request.query_params
filter_params_dict = {k: str(v) for (k, v) in filter_params.dict().items()
if v is not None and str(v) != ""}
print('DICT', filter_params_dict)
queryset = Product.objects.filter(**filter_params_dict)
return queryset
EDIT 2:
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
meat_type = models.ForeignKey(MeatType,
on_delete=models.CASCADE)
name = models.CharField(max_length=150,
db_index=True)
slug = models.SlugField(max_length=150,
db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
default='no-image.png')
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('price',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:detail',
args=[self.category.slug, self.id, self.slug])
You are using the incorrect url ,you should use this url for your custom action:
/api/shop/get_products/
The url you are using i.e /api/shop/ will call the default list action of the viewset not your custom action and thats why you are getting 200 status code always
You can read more about viewset here:
ViewSets
I need to send parameters to the serializer that do not exist in the model, so the serializer delete this data
I also have a nested serializer with a custom .create() function
This is the request data sended by the frontend ajax.
request data = {'data': [{'usuario': 269, 'coworkers': [328, 209], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24068, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}, {'usuario': 269, 'coworkers': [208, 212], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24067, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}]}
Model:
class TiempoOperacion(models.Model):
inicio = models.DateTimeField(blank=True, null=True)
fin = models.DateTimeField(blank=True, null=True)
operacion = models.ForeignKey(Operacion, related_name='tiempos', on_delete=models.CASCADE)
cantidad = models.IntegerField(default=0)
usuario = models.CharField(max_length=40)
motivo_pausa = models.CharField(max_length=140, default=None, null=True)
estado = models.CharField(
max_length=15,
choices=TASKS_STATUS_CHOICES,
default=UNACTION,
)
Viewset:
class TiempoOperacionViewSet(CustomViewSet):
model_class = TiempoOperacion
serializer_class = TiempoOperacionSerializer
pagination_class = SmallResultsSetPagination
order_by = '-inicio'
def create(self, request):
datos = request.data.get('listorders') if 'listorders' in request.data else request.data
tiemposerializer = self.serializer_class(data=datos, many=True, fields=('coworkers', 'operacion'))
if tiemposerializer.is_valid():
tiemposerializer.save()
return Response(tiemposerializer.data)
else:
return Response(tiemposerializer.errors, status=status.HTTP_400_BAD_REQUEST)
Serializer:
class TiempoOperacionSerializer(serializers.ModelSerializer):
operacion = OperacionSerializer()
class Meta:
model = TiempoOperacion
fields = '__all__'
def create(self, validate_data):
operacion_data = validate_data.pop('operacion')
print (f"\n\n validate_data : {validate_data} \n\n")
if not operacion_data:
raise ValidationError({
'operacion': 'This field object is required.'
})
coworkers = validate_data.get('coworkers')
query_operaciones = Operacion.objects.filter(**operacion_data)[:1]
if query_operaciones.count() > 0:
operacion = query_operaciones[0]
else:
operacion = Operacion.objects.create(**operacion_data)
tiempo_obj = validate_data
tiempo = TiempoOperacion.objects.create(operacion=operacion, **tiempo_obj)
if coworkers:
tiempos_list = []
for coworker in coworkers:
tiempo_obj.update({'usuario': coworker})
tiempos_list.append(TiempoOperacion(operacion=operacion, **tiempo_obj))
tiempos = TiempoOperacion.objects.bulk_create(tiempos_list)
return tiempo
I hope to get coworkers in create serialize function
But I only have:
validate_data : {'inicio': datetime.datetime(2019, 1, 24, 18, 12, 25, 251000, tzinfo=<DstTzInfo 'America/Bogota' -05-1 day, 19:00:00 STD>), 'usuario': '269', 'estado': 'progress'}
Re-write the to_internal_value function
class TiempoOperacionSerializer(serializers.ModelSerializer):
operacion = OperacionSerializer()
class Meta:
model = TiempoOperacion
fields = '__all__'
def create(self, validate_data):
operacion_data = validate_data.pop('operacion')
if not operacion_data:
raise ValidationError({
'operacion': 'This field object is required.'
})
coworkers = validate_data.pop('coworkers')
query_operaciones = Operacion.objects.filter(**operacion_data)[:1]
if query_operaciones.count() > 0:
operacion = query_operaciones[0]
else:
operacion = Operacion.objects.create(**operacion_data)
tiempo_obj = validate_data
tiempo = TiempoOperacion.objects.create(operacion=operacion, **tiempo_obj)
if coworkers:
tiempos_list = []
for coworker in coworkers:
tiempo_obj.update({'usuario': coworker})
tiempos_list.append(TiempoOperacion(operacion=operacion, **tiempo_obj))
tiempos = TiempoOperacion.objects.bulk_create(tiempos_list)
return tiempo
#This function rewrite the value validated_data mentioned in above function
def to_internal_value(self, data):
if not "coworkers" in data:
data['coworkers'] = []
return data