我有 4-5 种型号如下:-
class Product(models.Model):
title = models.CharField(max_length=255)
short_description = models.TextField(blank=True,null=True)
video_link = models.URLField(blank=True,null=True)
price = models.IntegerField(db_index=True,blank=True,null=True)
user = models.ForeignKey(User)
@staticmethod
def get_product_details(product,category=None,image=None,comment=None,rating=None):
product_detail = {
'id' : product.id,
'title' : product.title,
'short_description' : product.short_description,
'video_link' : product.video_link,
'price' : product.price,
'user' : product.user.first_name + ' ' + product.user.last_name,
}
if category:
product_detail.update({'categories': ProductCategory.get_product_categories(product)})
if comment:
product_detail.update({'comments' : ProductComments.get_product_comments(product)})
if image:
product_detail.update({'images': ProductImages.get_product_images(product)})
if rating:
product_detail.update({'rating': ProductRating.return_data(product)})
return product_detail
class ProductCategory(models.Model):
subcategory = models.CharField(max_length=255)
product = models.ForeignKey(Product)
date = models.DateTimeField(auto_now_add=True)
@staticmethod
def get_product_categories(product):
return ProductCategory.objects.filter(product=product).values_list('subcategory',flat=True)
同样,我有多个用Product
FK 引用的模型(例如ProductImages
等ProductComments
),我需要从中获取数据,然后在获取特定产品的数据时在Product
模型使用下共同显示它。get_product_details
所以,如果我浏览到localhost:8080/product/<product_id>
,它会调用 , get_product_details
这又会调用模型中的其他方法来收集信息参考<product_id>
。
是否可以在 Django-Rest-Framework 中创建一个序列化程序,该序列化程序将从引用特定产品对象的其他序列化程序获取数据。?
以下是我的序列化程序。
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
class ProductCategorySerializer(serializers.ModelSerializer):
class Meta:
model = ProductCategory
我期待的是这样的: -
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
include_data_models = (ProductCategory,ProductImages,)
我的预期输出应采用以下格式:-
[
{
"price": 1234,
"categories": [
"Tech"
],
"id": 1,
"title": "1",
"user": "user full name from User's model",
"video_link": "",
"short_description": ""
}
]