I'm using Django RestFramework to create a simple eCommerce API where one product could have many images and I would like to get the URLs of all these images on a json field.
For now, I got the first image url using "imagembicicleta_set.all.first.image.url" on the serializer, but I need all URLs list:
{
"count": 7,
"next": null,
"previous": null,
"results": [
{
"id": 1,
"nome": "Specialized Roubaix",
"marca__nome": "Specialized",
"categoria": "Bicicletas de Estrada",
"atividades": [
1
],
"terrenos": [
"Asfalto"
],
"preco": "16999.00",
"ano": 1,
"absolute_url": "/bicicletas/Specialized/specialized-roubaix-2020/",
"img_url": "/media/images/bicicletas/roubaix1.jpeg"
},
{
"id": 2,
"nome": "Specialized Roubaix Sport",
"marca__nome": "Specialized",
Following how is my setup:
Models.py
class Bicicleta(models.Model):
id = models.AutoField(primary_key=True)
nome = models.CharField(max_length=200, blank=False, null=False)
slug = models.SlugField(unique=True)
status = models.IntegerField(choices=STATUS_CHOICES, default=1, blank=False, null=False)
descricao = RichTextField(blank=True, null=True)
marca = models.ForeignKey(MarcaBicicleta, blank=True, null=True, on_delete=models.SET_NULL)
...
class ImagemBicicleta (models.Model):
bicicleta = models.ForeignKey(Bicicleta, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/bicicletas')
Serializer.py
class BicicletasSerializer(serializers.ModelSerializer):
marca__nome = serializers.CharField(source='marca.nome')
categoria = serializers.CharField(source='categoria.nome')
terrenos = serializers.StringRelatedField(many=True)
absolute_url = serializers.URLField(source='get_absolute_url', read_only=True)
img_url = serializers.URLField(source='imagembicicleta_set.all.first.image.url', read_only=True) #I could get the first image using this
class Meta:
model = Bicicleta
fields = ['id', 'nome', 'marca__nome', 'categoria', 'atividades', 'terrenos', 'preco', 'ano', 'absolute_url', 'img_url']
views.py
class BicicletasView(generics.ListAPIView):
serializer_class = BicicletasSerializer
queryset = Bicicleta.objects.all()
filter_backends = (DjangoFilterBackend, SearchFilter)
filterset_fields = ['marca', 'terrenos', 'status']
search_fields = {'nome': ['icontains'], }
How could I get all images URLs in the field?
Per example, if a product has 3 different images, I would expect to have the img field like this:
"img_url": [ "/media/images/bicicletas/roubaix1.jpeg","/media/images/bicicletas/roubaix2.jpeg","/media/images/bicicletas/roubaix3.jpeg" ],
You can add a method serializer which will collect all the urls for each individual object like this:
class BicicletasSerializer(serializers.ModelSerializer):
marca__nome = serializers.CharField(source='marca.nome')
categoria = serializers.CharField(source='categoria.nome')
terrenos = serializers.StringRelatedField(many=True)
absolute_url = serializers.URLField(source='get_absolute_url', read_only=True)
img_url = serializers.SerializerMethodField()
def get_image_url(self , instance):
return ImagemBicicleta.objects.filter(bicicleta=instance).values_list('image',flat=True)
class Meta:
model = Bicicleta
fields = ['id', 'nome', 'marca__nome', 'categoria', 'atividades', 'terrenos', 'preco', 'ano', 'absolute_url', 'img_url']
Related
I have two serializers:
class AlbumImageSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField('get_url')
def get_url(self, obj):
return obj.image.url
class Meta:
model = AlbumImage
fields = ['id', 'url']
class PhotoAlbumSerializer(serializers.ModelSerializer):
photos = AlbumImageSerializer(many=True, read_only=True)
class Meta:
model = PhotoAlbum
fields = ('id', 'name', 'photos')
And i read that to display full url of image it's enough to pass a request context to serializer call, like:
serialized = SomeSerializer(some, context={"request": request})
And when you use ViewSet you don't need to do anything, DRF will automatically pass the request context while initializing the serializer.
I am using ViewSets like:
class PhotoAlbumViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
GenericViewSet):
serializer_class = PhotoAlbumSerializer
but still my get-request returns response like:
"url": "/media/images/photo.jpg"
How can i get
"url": "127.0.0.1:8000/media/images/photo.jpg"
In my case?
My models
class PhotoAlbum(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True)
name = models.CharField(max_length=50, verbose_name='Pet name')
class AlbumImage(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True)
album = models.ForeignKey(PhotoAlbum, on_delete=models.CASCADE, related_name='photos')
image = models.ImageField(upload_to='images/', height_field=None, width_field=None, max_length=100, blank=True)
Another endpoint where print url return the response like 127.0.0.1:8000/media/UUID/photo.jpg:
#action(methods=['post'], detail=True)
def photo(self, request, pk):
file = request.data['file']
album = PhotoAlbum.objects.get(pk=pk)
alb_img = AlbumImage(album=album, image=file)
alb_img.save()
return Response({'id': pk,
'url': alb_img.image)})
Just do not try to override the url field, let the framework take care of it for you:
serializers.py
class AlbumImageSerializer(serializers.ModelSerializer):
class Meta:
model = models.AlbumImage
fields = ['id', 'url']
class PhotoAlbumSerializer(serializers.ModelSerializer):
photos = AlbumImageSerializer(many=True, read_only=True)
class Meta:
model = models.Pet
fields = ('id', 'name', 'photos')
sample output:
[
{
"id": 1,
"name": "Pet name.",
"photos": [
{
"id": 2,
"url": "http://localhost:8000/media/random_image_one.png"
},
{
"id": 3,
"url": "http://localhost:8000/media/random_image_two.png"
}
]
}
]
I am trying to add field amount into Ingredient model, by creating an intermediary model IngredientAmount. But I am struggling with serialization.
The response should look like this:
"results": [
......
"ingredients": [
{
"id": 0,
"name": "Potato",
"measurement_unit": "kg",
"amount": 1
}
],
....
]
I am using IngredientAmountSerializer(serializers.ModelSerializer), but Django says that I am in 'Ingredient' object and it has no attribute 'amount'.
what am I doing wrong?
models
class Ingredient(models.Model):
name = models.CharField(max_length=200)
measurement_unit = models.CharField(max_length=200)
class Meta:
ordering = ['id']
def __str__(self):
return self.name
class IngredientAmount(models.Model):
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE,
related_name='ingredient_amount')
recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE,
related_name='ingredient_amount')
amount = models.SmallIntegerField(
validators=(
validators.MinValueValidator(
1, 'add amount'),))
class Recipe(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
ingredients = models.ManyToManyField(
Ingredient, through=IngredientAmount,
through_fields=('recipe', 'ingredient', ),
)
tags = models.ManyToManyField(Tag, blank=True, related_name='recipe')
image = models.ImageField()
name = models.CharField(max_length=200)
text = models.TextField()
cooking_time = models.PositiveSmallIntegerField(
validators=(
validators.MinValueValidator(1, message='choose time'),
),
)
serializers
class IngredientAmountSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='ingredient.name', read_only=True)
measurement_unit = serializers.IntegerField(source='ingredient.measurement_unit', read_only=True)
class Meta:
model = IngredientAmount
fields = ('id', 'name', 'measurement_unit', 'amount' )
class RecipeSerializer(serializers.ModelSerializer):
author = AuthorSerializer()
tags = TagSerializer(read_only=True, many=True)
image = Base64ImageField(required=True)
ingredients = IngredientAmountSerializer( read_only=True, many=True)
class Meta:
model = Recipe
fields = ('id', 'tags', 'author', 'name', 'image', 'text',
'cooking_time', 'ingredients')
I gues the problem is, you are trying to serialize Ingredient model with IngredientAmountSerializer when in it Meta model is IngredientAmount, and not Ingredient.
Update: If you want serialize IngredientAmount, try to use source
class RecipeSerializer(serializers.ModelSerializer):
...
ingredients = IngredientAmountSerializer(source='ingredientamount_set', read_only=True, many=True)
I'm trying to make an API for a butcher.
With this API and the website that I will build by the next, the client will be able to make his order remotly.
Here is my probleme.
With the order form, the client send me JSON data like here :
{
"user": 8,
"orderDay": "2020-06-24",
"deliveryDay": "2020-06-30",
"deliveryAddress": "Place des FĂȘtes",
"comment": "",
"orderDetail":
[
{
"product": 2,
"byProduct": 2,
"quantity": 43
},
{
"product": 3,
"byProduct": 3,
"quantity": 5
}
]
}
These data must be saved in the database.
These are the models that I use : models.py
class order(models.Model):
user = models.ForeignKey(memberArea, on_delete=models.CASCADE)
comment = models.TextField(null=True, blank=True)
orderDay = models.DateTimeField(auto_now_add=True)
deliveryDay = models.DateField()
deliveryAddress = models.CharField(max_length=255)
state = models.CharField(max_length=255)
price = models.TextField(null=True, blank=True)
response = models.TextField(null=True, blank=True)
class orderDetail(models.Model):
order = models.ForeignKey(order, on_delete=models.CASCADE)
product = models.ForeignKey(product, on_delete=models.CASCADE)
byProduct = models.ForeignKey(byProduct, on_delete=models.CASCADE)
quantity = models.CharField(max_length=255)
class product(models.Model):
name = models.CharField(max_length=255)
prix_uni = models.TextField(null=True, blank=True)
prix_kg = models.TextField(null=True, blank=True)
dispo = models.BooleanField(null=True, blank=True)
category = models.ForeignKey(category, on_delete=models.CASCADE)
redu = models.TextField(null=True, blank=True)
class byProduct(models.Model):
product = models.ForeignKey(product, on_delete = models.CASCADE)
name = models.CharField(max_length=255)
I make a serializer file like this serializer.py
class orderDetailSerializer(serializers.ModelSerializer):
order = serializers.PrimaryKeyRelatedField(many=False, queryset = order.objects.all())
class Meta:
model = orderDetail
fields = '__all__'
class OrderSerializer(serializers.ModelSerializer):
orderDetail = orderDetailSerializer(many=True)
class Meta:
model = order
fields = ['user', 'comment', 'deliveryAddress', 'deliveryDay', 'orderDetail']
def create(self, validated_data):
order_detail_data = validated_data.pop('orderDetail')
new_order = order.objects.create(**validated_data)
new_order.save()
for product in order_detail_data:
order_detail = orderDetail.objects.create(order=new_order, **product)
new_order.orderDetail.add(order_detail.id)
return new_order
And this is my view : views.py:
#Make an order
#api_view(['POST'])
def order(request, format=None):
if request.method == 'POST':
serializer = OrderSerializer(data=request.data)
data = {}
if serializer.is_valid():
serializer.save()
data['response'] = "Your order went well"
return Response(data)
return Response(serializer.errors)
When I try to run my code, it tells me that the order data is missing :
{
"orderDetail": [
{
"order": [
"This field is required."
]
},
{
"order": [
"This field is required."
]
}
]
}
I don't know how to add this because the order_id that I need is created at the same time that the orderDetail.
Thank's by advance for helping me.
you should make order field readonly in orderDetailSerializer:
class orderDetailSerializer(serializers.ModelSerializer):
class Meta:
model = orderDetail
fields = '__all__'
read_only_fields = ('order',)
I don't know how to merge all refetch_related objects from MeasurememtResult table to one list objects:
models.py
class DeviceMeasurement(models.Model):
patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.CASCADE)
device = models.ForeignKey(Device, on_delete=models.CASCADE)
created_date = models.DateTimeField()
front_id = models.UUIDField(blank=True, null=True)
class MeasurememtResult(models.Model):
measurement_result = models.FloatField()
measurement_type = models.CharField(choices=MEASUREMENT_TYPES, max_length=30)
device_measurement_id = models.ForeignKey(DeviceMeasurement, related_name='res_data', on_delete=models.CASCADE)
views.py
class GetMeasurements(viewsets.GenericViewSet, mixins.ListModelMixin):
permission_classes = (IsAuthenticated,)
serializer_class = GetMeasurementsSerializer
queryset = DeviceMeasurement.objects.values('patient__first_name', 'device__id', 'created_date', 'front_id',
'results__measurement_result',
'results__measurement_type').prefetch_related('res_data').all()
serializers.py
class GetMeasurementsSerializer(serializers.Serializer):
created_date = serializers.DateTimeField()
front_id = serializers.UUIDField()
patient__first_name = serializers.CharField()
device__id = serializers.IntegerField()
results__measurement_result = serializers.IntegerField()
results__measurement_type = serializers.CharField() `
So, I got Response like as:
[
{
"created_date": "2020-06-05T15:03:22.481032+03:00",
"front_id": null,
"patient__first_name": "Alex",
"device__id": 8,
"results__measurement_result": 100,
"results__measurement_type": "blood_pressure_SYS"
},
{
"created_date": "2020-06-05T15:03:22.481032+03:00",
"front_id": null,
"patient__first_name": "Alex",
"device__id": 8,
"results__measurement_result": 120,
"results__measurement_type": "blood_pressure_DIA"
}
]
But I should return list of MeasurememtResult objects like as:
In 2 objects i have equal values of device_id.
{
"created_date": "2020-06-05T15:03:22.481032+03:00",
"front_id": null,
"patient__first_name": "Alex",
"device__id": 8,
"res_data": [
{
"results__measurement_result": 120,
"results__measurement_type": "blood_pressure_DIA"
},
{
"results__measurement_result": 100,
"results__measurement_type": "blood_pressure_SYS"
}
]
}
Prefetch related is for database query optimization . It has no relation with how your response is structured .
To return queryset with distinct device id ,
queryset = DeviceMeasurement.objects.all().distinct("device").prefetch_related('res_data')
Note that the distinct("fieldname") will only work if you using postgres database .Please research on how to get it working in your database.
Select DISTINCT individual columns in django?
Then in your serializer:
class MeasurementResultSerializer(serializers.ModelSerializer):
class Meta:
model = MeasurememtResult
fields = "__all__"
read_only_fields = fields
class GetMeasurementsSerializer(serializers.Serializer):
res_data = serializers.SerializerMethodField()
created_date = serializers.DateTimeField()
front_id = serializers.UUIDField()
patient__first_name = serializers.CharField()
device__id = serializers.IntegerField()
def get_res_data(self, instance):
return MeasurementResultSerializer(instance.res_data.all(), many=True).data
You can edit this with your required fields , Inside fields array you can give fields like :
fields = ["measurement_result", "measurement_type"]
I have first made category crud, and then product crud with many-to-many relation with category.
models.py (category):
class Category(models.Model):
name = models.CharField(max_length=191, blank=False, null=False)
description = models.TextField(blank=True, null=True)
models.py (product):
class Product(models.Model):
product_code = models.CharField(max_length=191, blank=False, null=False)
name = models.CharField(max_length=191, blank=False, null=False)
description = models.TextField(blank=False, null=False)
price = models.DecimalField(max_digits=19, decimal_places=2)
photo = models.ImageField(upload_to='pictures/products/', max_length=255, null=False, blank=False)
category = models.name = models.ManyToManyField(Category)
How to achieve following result:
{
"categories": [
{
"id": 1,
"name": "Indoor Muscle Training",
"description": null,
"products":{
"name":"product_name",
"code":"product_code"
}
},
{
"id": 2,
"name": "Outdoor Muscle Training",
"description": null,
"products":{
"name":"product_name",
"code":"product_code"
}
}
]
}
using serializer-method field can be an option for this case. Our goal is get product information from category serializer. So for this
class CategorySerializer(serializers.ModelSerializer):
products = serializers.SerializerMethodField()
class Meta:
model = Category
fields = ('') # add relative fields
def get_products(self, obj):
products = obj.product_set.all() # will return product query set associate with this category
response = ProductSerializer(products, many=True).data
return response