I have 4 different types of model and I want to create a serializer for one model where I can do the CRUD for all of them at once.
My Models:
class PropertyType(models.Model):
class Category(models.Model):
class Property(models.Model):
property_type = models.ForeignKey(PropertyType, on_delete=models.CASCADE, verbose_name="Property Type")
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Property Category")
class Images(models.Model):
property = models.ForeignKey(Property, on_delete=models.CASCADE)
Serializes:
from django.db.models import fields
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, Serializer
from . models import Category, Images, Property, PropertyType
class CategorySerializer(ModelSerializer):
class Meta:
model = Category
fields = "__all__"
class PropertyTypeSerializer(ModelSerializer):
class Meta:
model = PropertyType
fields = "__all__"
class ImageSerializer(ModelSerializer):
class Meta:
model = Images
fields = ["id", "url"]
class GetPropertySerializer(ModelSerializer):
property_img = ImageSerializer(many=True)
property_type = PropertyTypeSerializer()
category = CategorySerializer()
class Meta:
model = Property
fields = [
"id",
"name",
"rent_cost",
"primary_cost",
"bedrooms",
"kitchen",
"bathroom",
"property_size",
"furnished",
"description",
"localtion",
"category",
"property_img",
"landmark",
"latitude",
"longitude",
"is_featured",
"on_sale",
"sold",
"property_age",
"property_type",
"category",
"created_at",
"updated_at"
]
class CreatePropertySerializer(ModelSerializer):
property_img = ImageSerializer(many=True)
property_type = serializers.PrimaryKeyRelatedField(
read_only=False, queryset=PropertyType.objects.all())
category = serializers.PrimaryKeyRelatedField(
read_only=False, queryset=Category.objects.all())
class Meta:
model = Property
fields = [
"id",
"name",
"rent_cost",
"primary_cost",
"bedrooms",
"kitchen",
"bathroom",
"property_size",
"property_img",
"furnished",
"description",
"localtion",
"category",
"landmark",
"latitude",
"longitude",
"is_featured",
"on_sale",
"sold",
"property_age",
"property_type",
"category",
"created_at"
]
def create(self, validated_data):
images = validated_data.pop('property_img')
property = Property.objects.create(**validated_data)
for img in images:
Images.objects.create(**img, property=property)
return property
Here is the github url Github repo url
Currently I can create all of them at once with property
model but the serializer returns only foreignkey fields id after creating an instance.
I have searched on Google but couldn’t find a better result where I can do all of them from one serializer.
Please help me it will be life saving for me, I have been stuck with this approach for the past few weeks.