I have 3 models: Product, Trust and Store. Product and Trust both has store as a foreign key. In model serializer of Product how to get data from the trust table?
First I used SerializerMethodField for getting data from the trust, it will make db queries for each product, that will cause longer respond time as the product queryset get bigger.
Is there any way I can use select related to get the data in the model Trust so that it will reduce the db queries?
This is the current code.
models.py
class Product(ModelDiffMixin, models.Model):
productid = models.AutoField(primary_key=True)
product_reference = models.CharField(max_length=15, unique=True)
product_name = models.CharField(max_length=200)
store_reference = models.ForeignKey(
"stores.Store",
null=True,
to_field="store_reference",
related_name="store_products",
on_delete=models.CASCADE,
db_column="store_reference",
)
class Store(models.Model):
storeid = models.AutoField(primary_key=True)
store_reference = models.CharField(max_length=15, unique=True)
store_name = models.CharField(max_length=100)
class Trust(models.Model):
trustcenterid = models.AutoField(primary_key=True)
store_reference = models.ForeignKey(
"stores.Store",
to_field="store_reference",
on_delete=models.CASCADE,
related_name="store_details",
db_column="store_reference",
)
city = models.CharField(max_length=100, null=True, blank=True)
views.py
class GetStoreProducts(APIView):
def get(self, request, store_reference):
products = Product.objects.filter(
store_reference=store_reference, hide=False, deleted=False
).order_by("-created_date").select_related('store_reference')prefetch_related('prod_images')
serializer_copy = GetProductSerializer(qs, many=True).data
return Response(
{"message": "success", "data": serializer_copy}, status=status.HTTP_200_OK
)
serailizers.py
class GetProductSerializer(serializers.ModelSerializer):
prod_images = ProductImagesSerializer(many=True, source="available_product_images")
store_name = serializers.CharField(source="store_reference.store_name")
location = serializers.SerializerMethodField("get_location")
class Meta:
model = Product
fields = [
"product_name",
"store_name",
"prod_images",
"location"
]
def get_location(self, obj):
if TrustCenter.objects.filter (store_reference=obj.store_reference).exists ():
trust_center = TrustCenter.objects.get (store_reference=obj.store_reference)
location = trust_center.city
else:
location = None
return location
What I am expecting is, Instead of using this SerializerMethodField to get the data from the model Trust table is there any other way?
store_name = serializers.CharField(source="store_reference.store_name")
I can get this store_name using the above, since select_related has used it will do multiple queries. Like this, is it possible to get the field city from the Trust table?