I'm trying to combine rasters model field with non-model config_version field into my serializer which looks like:
class RasterPostSerializer(serializers.ModelSerializer):
class Meta:
model = Raster
fields = (
'name',
'description',
'filepath'
)
class ConfigurationSerializer(serializers.Serializer):
config_version = serializers.CharField()
rasters = RasterPostSerializer(many=True)
def create(self, validated_data):
data_field = validated_data['rasters']
for raster in data_field['rasters']:
return Raster(name=raster['name'], description=raster['description'], filepath=raster['filepath'])
Before utilize serializer.save() method I would like to check config_version in my view.py, but after that the .save() gives me:
The serializer field might be named incorrectly and not match any attribute or key on the `Raster` instance.
Original exception text was: 'Raster' object has no attribute 'config_version'.
What is going on, and is there a solution for that?
EDIT:
my example JSON POST payload looks like:
{
"config_version":"v2",
"rasters":[
{
"name":"XYZ.jpg",
"description":"some description",
"filepath":"path in filesystem"
}
}
The config_version it is not constant. It can be set dynamically, due the controller utilizing ConfigurationSerializer will be the configuration endpoint - there need to be possibility to add rasters, and some other information in the future.
configuration endpoint in views.py looks like
#api_view(['POST'])
def configuration(request):
if request.method == 'POST':
serializer = ConfigurationSerializer(data=request.data)
if serializer.is_valid():
if serializer.validated_data['config_version'] is 'v2':
raster_name_list = [raster.name for raster in Raster.objects.all()]
for instance in serializer.validated_data['rasters']:
if instance['name'] in raster_name_list:
return Response({"Fail": "Raster name '{}' already exists".format(instance['name'])}, status=status.HTTP_304_NOT_MODIFIED)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
You should return ConfigurationSerializer data as the result of create action. And also i have no idea what you are going to do with config_version
class ConfigurationSerializer(serializers.Serializer):
config_version = serializers.CharField()
rasters = RasterPostSerializer(many=True)
def create(self, validated_data):
config_version = validated_data.get('rasters')
rasters = validated_data.pop('rasters')
raster_list = []
for raster in rasters:
raster_list.append(Raster.objects.create(**raster))
return {
"config_version": config_version,
"rasters": raster_list
}
You need a SerializerMethodField: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
config_version = SerializerMethodField()
def get_config_version(self, obj):
return YOUR_CUSTOM_DATA
Related
I'm having trouble handling DoesNotExist error, Im using DRF and DRF-Nested-Routers and when I create a new Like object I need the Photo PK so I can add it to the Like object.
I'm trying to catch the error that I get when the Photo with that PK doesn't exist.
This is how I'm doing the creation of the Like in the serializer:
class LikeModelSerializer(serializers.ModelSerializer):
""" Like model serializer. """
user = serializers.CharField(default=serializers.CurrentUserDefault())
class Meta:
""" Meta class. """
model = Like
fields = ('user', 'photo')
read_only_fields = ('user', 'photo')
def create(self, validated_data):
# Get the photo pk from the view context (DRF-nested-routers) and
# create the new like with the validated_data
photo_pk = self.context['view'].kwargs["photo_pk"]
try:
photo = Photo.objects.get(id=photo_pk)
except Photo.DoesNotExist:
return Response(data={'detail': "The photo doesn't exist."}, status=status.HTTP_404_NOT_FOUND)
validated_data["photo"] = photo
like, created = Like.objects.get_or_create(**validated_data)
if created:
photo.total_likes += 1
photo.save()
return like
The perform_create of the view:
def perform_create(self, serializer):
""" Creates a new like.
The substraction in the total_likes is made in the serializer.
"""
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(data=serializer.data, status=status.HTTP_200_OK)
The response I get with this is: {'user': 'my username here'}
I also tried with except Photo.DoesNotExist but it gives the same result.
It migth be more clear to perform the check in the validate method of the serializer class. In case of photo absence raise the serializers.ValidationError.
I have not test the code but I think that it works.
class LikeModelSerializer(serializers.ModelSerializer):
...
def validate(self, attrs):
photo_pk = self.context['view'].kwargs["photo_pk"]
try:
photo = Photo.objects.get(id=photo_pk)
except Photo.DoesNotExist:
raise serializers.ValidationError({"detail": "The photo doesn't exist"})
attrs["photo"] = photo
return attrs
def create(self, validated_data):
# Get the photo pk from the view context (DRF-nested-routers) and
# create the new like with the validated_data
like, created = Like.objects.get_or_create(**validated_data)
if created:
photo.total_likes += 1
photo.save()
return like
def perform_create(self, serializer):
""" Creates a new like.
The substraction in the total_likes is made in the serializer.
"""
if not serializer.is_valid():
raise ValidationError(serializer.errors)
serializer.save()
return Response(data=serializer.data, status=status.HTTP_200_OK)
I want to store an array in my database. For that I use ArrayType of this type in my model: [[[0.29, 10.27]]]. I would like to use a serializer to create my GET, POST and PUT requests.
Here is my model:
models.py
class Area(models.Model):
osm = ArrayField(
ArrayField(
ArrayField(
models.FloatField(),
size=2,
),
),
)
Here is my serializer :
serializer.py
class AreaSerializer(serializers.ModelSerializer):
class Meta:
model = Area
fields = ['osm', ]
And here is my view :
views.py
class ShopAreaList(ShopCustomListView):
"""Get or create areas for a shop"""
queryset = Shop.objects.all()
lookup_field = 'path'
def get(self, request, path):
"""Depends on mustBeLogged to get areas of a shop"""
shop = self.get_object()
areas = Area.objects.filter(shop=shop)
serializer = AreaSerializer(areas, many=True)
return Response(serializer.data)
def post(self, request, path):
"""For admin or shop owner to create areas"""
shop = self.get_object()
serializer = AreaSerializer(data=request.data)
if serializer.is_valid():
serializer.save(shop=shop)
return Response(serializer.data)
return Response(serializer.errors)
Here is the data I get:
{
"osm": [[[0.29, 10.27]]]
}
When I try to run my POST method I get this error:
Error binding parameter 0 - probably unsupported type.
I don't know what can I do to fix this error.
Thank you in advance for your help
I'm working on a small project Django Rest Framework, I already create add contact function as you can see in my create function. now I'm working on bulk import, but when I submit my data as a list not as a dict I get an error message :
{"non_field_errors":["Invalid data. Expected a dictionary, but got list."]}
this is my code to add a contact,
class ContactView(ListModelMixin, viewsets.GenericViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
def create(self, request):
serializeObject = ContactSerializer(data = request.data)
if serializeObject.is_valid():
serializeObject.save()
contactObject = Contact.objects.all()
contactSerializer = ContactSerializer(contactObject, many=True)
return Response(contactSerializer.data, status = status.HTTP_201_CREATED)
return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST)
Now i would like to create another function, for bulk create, since i have a list
This is my header data structure :
[{"Greeting":"amine","first_name":"alain","last_name":"amine","title":"ricardo","language":"ab#xyz.com","email":43822510594,"phone_1":43822510594,"phone_2":"not yet","mobile":43822510594,"fax":"not yet","internal_id":"xname"},{"Greeting":"bill","first_name":"microsoft","last_name":"bill","title":"microsoft","language":"bill#microsoft.com","email":652565455,"phone_1":652565455,"phone_2":"new york","mobile":652565455,"fax":"new york","internal_id":"microsoft"},{"Greeting":"john","first_name":"Yoyo","last_name":"Ruth","title":"xnameagain","language":"rh#xyz.com","email":5465559852,"phone_1":5465559852,"phone_2":"Vancouver","mobile":5465559852,"fax":"Vancouver","internal_id":"yname"}]
This is my serializer:
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = "__all__"
I found the Solution on https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects
all what i have to do is to add many=True to create multiple object
serializeObject = ContactSerializer(data = request.data, many=True)
Create method should look like this:
class ContactView(ListModelMixin, viewsets.GenericViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
def create(self, request):
valid_objects = []
for data in request.data:
serializeObject = ContactSerializer(data=data)
if serializeObject.is_valid():
valid_objects.append(serializeObject)
else:
return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST)
for obj in valid_objects:
obj.save()
contactObject = Contact.objects.all()
contactSerializer = ContactSerializer(contactObject, many=True)
return Response(contactSerializer.data, status = status.HTTP_201_CREATED)
Advise
They may not be the best practices but it works.
I want to set user_id field using JWT token and store in database table when new reservation is created. there can be single or multiple reservation request.
whenever user create reservation i want to store there user_id in our table. currently there is no foreign key associated with it. it is simply an integer field.
I am able to fetch user_id from JWT.but its not updating in database
I know this question had been asked previously i tried all the answer of previous post but its not working for me. i dont know why
model.py
class reservations(models.Model):
pet_id=models.IntegerField()
user_id=models.IntegerField(default=0)
location=models.PositiveSmallIntegerField()
arrival=models.DateTimeField()
depature=models.DateTimeField()
comments=models.TextField(max_length=200)
view.py
class requestReservation(CreateAPIView):
serializer_class = requestReservationSerailizer
permission_classes = [IsAuthenticated]
def create(self, request, *args, **kwargs):
serializer = requestReservationSerailizer(data=request.data,context={'user_id': request.user.id}, many=True)
if not serializer.is_valid(raise_exception=False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK)
serializer.py
class requestReservationSerailizer(ModelSerializer):
user_id = SerializerMethodField('set_user_id')
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def set_user_id(self, obj):
obj.user_id = self.context.get("user_id")
return obj.user_id
currently it is simply storing user_id as 0 which is default set in model.
SerializerMethodField is read-only by default, here's a quick look at the source code:
def __init__(self, method_name=None, **kwargs):
self.method_name = method_name
kwargs['source'] = '*'
kwargs['read_only'] = True
super(SerializerMethodField, self).__init__(**kwargs)
Assuming you want to read and write into this field; remove the SerializerMethodField overriding from the serializer declaration; and set the user_id in your view
class requestReservationSerailizer(ModelSerializer):
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def create(self, request, *args, **kwargs):
data = request.data.copy()
for datum in data:
datum['user_id'] = request.user.id
serializer = requestReservationSerailizer(data=data, many=True)
if not serializer.is_valid(raise_exception=False):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({"message":"Success","status_message":"Reservation Created Successfully"},status=status.HTTP_200_OK)
Ofcourse; if you don't want your view to be doing this (and I'd agree with you here), then pass it in context (explicit) or use self.request.user.id and override validate_user_id
class requestReservationSerailizer(ModelSerializer):
class Meta:
model=reservations
fields = [
'pet_id',
'user_id',
'location',
'arrival',
'depature',
'comments',
]
def validate_user_id(self, value):
user_id = self.context.get('user_id', None) # Assuming you continue to pass it in context
if user_id is None:
# Handle error
return user_id
# You can also do this; might raise an AttributeError if the user is not authenticated:
# return self.request.user.id
I need to update categories in many Article in one request.
In ArticleViewSet I have:
def get_serializer_class(self):
if self.action in ['partial_update', 'update']:
return ArticlePostSerializer
return ArticleSerializer
So ArticlePostSerializer need to be changed.
This is my serializers code:
class ArticleShortCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = 'id', 'name'
class ArticleSerializer(serializers.ModelSerializer):
categories = serializers.SerializerMethodField()
def get_categories(self, obj):
return ArticleShortCategorySerializer(obj.categories, many=True).data
class Meta:
model = Article
read_only_fields = 'id'
fields = ('categories', 'text') + read_only_fields
class ArticlePostSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = 'id', 'categories', 'text'
I tried to add:
class ArticlePostListSerializer(serializers.ListSerializer):
and
class Meta:
list_serializer_class = ArticlePostListSerializer
But it doen't work.
How to change this code to do multiple update.
My json request
{
[id: 90, categories: [10,12,14]],
[id: 93, categories: [10,12,14]],
[id: 95, categories: [10,12,14]]
}
Here is sample of CreateMixins OR UpdateMixins you requested.
======================= VIEW ================================
class OrderCreate(mixins.CreateModelMixin,viewsets.GenericViewSet):
pagination_class = None
def get_queryset(self):
return []
def get_serializer_class(self):
return serializers.OrderSerializer
======================= Serializer =============================
class OrderDetailSerializer(serializers.ModelSerializer):
class Meta:
model = crm_models.OrderDetail
fields = (
'product',
'quantity',
'rate_per_unit',
'order_quantity'
)
class OrderSerializer(serializers.ModelSerializer):
order_details = OrderDetailSerializer(many = True)
class Meta:
model = crm_models.OrderMaster
fields = (
'order',
'invoice_number',
'client',
'beat_check',
'target_customer',
'order_editor_client_employee',
'order_marked',
'order_saved',
'edit_marked',
'edit_saved',
'adhoc',
'order_details'
)
def create(self, validated_data,*args,**kwargs):
ordersdetails_data = validated_data.pop('order_details')
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
validated_data['client'] = user.client
validated_data['order_editor_client_employee'] = user
validated_data['adhoc'] = validated_data['adhoc'] if 'adhoc' in validated_data else False
orderObj = super(OrderSerializer, self).create(validated_data,*args,**kwargs)
orderdetails = []
for details in ordersdetails_data:
orderdetails.append(crm_models.OrderDetail(
product= details['product'],
quantity = details['quantity'],
rate_per_unit = details['rate_per_unit'],
order_quantity = details['order_quantity'],
order = orderObj
))
crm_models.OrderDetail.objects.bulk_create(orderdetails)
return orderObj
In Update view function name would be changed to update, you can find more documentation http://www.django-rest-framework.org/api-guide/generic-views/#createmodelmixin
I found K. Moe's answer to this question: Django Rest Framework POST Update if existing or create much easier to understand and implement. You only need to add a create method in the serializer and use mixins.CreateModelMixin, generics.GenericAPIView in the view. Then you can use a POST request, instead of PUT/PATCH. It allows to create AND update data stored in your database. My code for the view:
class ZipCodeList(mixins.CreateModelMixin, generics.GenericAPIView):
def post(self, request, format=None):
is_many = isinstance(request.data, list)
if is_many:
serializer = ZipCodeSerializer(data=request.data, many=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
serializer = ZipCodeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#Greg Holst, why so much duplication? Why not:
class ZipCodeList(mixins.CreateModelMixin, generics.GenericAPIView):
def post(self, request, format=None):
serializer = ZipCodeSerializer(data=request.data, many=isinstance(request.data, list))
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Anyway, that only worked for me for creating new objects, didn't work to create-or-update in one sweep (it kept telling me these objects already exist), so this is what I did:
class ContributorSyncListAPIView(ListAPIView):
permission_classes = (isSuperUserPermission,)
allowed_methods = ("GET", "PUT")
lookup_field = "airtable_id"
serializer_class = ContributorSyncSerializer # Doesn't get used in Put, just in Get.
model = Contributor
def get_queryset(self):
return self.model.objects.all()
def put(self, request, format=None):
objects = list(request.data)
# objects is a list of OrderedDicts
try:
for o in objects:
try:
instance = self.model.objects.get(
**{self.lookup_field: o.get(self.lookup_field)}
)
for key, value in o.items():
setattr(instance, key, value)
except self.model.DoesNotExist:
instance = self.model(**o)
instance.save()
return Response(objects, status=status.HTTP_200_OK)
except Exception as e:
return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)
Note my code above is very light on validation just because it was for a process of syncing models from one environment to another by a superuser, different environments with an identical codebase; so the assumption was the data had already been validated when the data was entered into the first environment. For any other purpose you'd want to validate more. But this is what I had to do to handle a list of objects that may need to be created or updating, on an object-by-object basis.