我有一个PurchaseDetail模型,如
class PurchaseDetail(NowTimestampAndUserModel):
purchase = models.ForeignKey(PurchaseMaster, default=False, related_name="purchase_details", on_delete=models.CASCADE)
item = models.ForeignKey(Item, default=False, on_delete=models.CASCADE)
item_category = models.ForeignKey(ItemCategory, default=False, on_delete=models.CASCADE)
purchase_cost = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)
sale_cost = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)
qty = models.FloatField(help_text="Purchase quantity")
ref_purchase_order_detail = models.PositiveIntegerField(default=0)
ref_purchase_detail = models.PositiveIntegerField(default=0)
我有“Item”模型和“item_category”模型作为 项目
class ItemCategory(NowTimestampAndUserModel):
name = models.CharField(max_length=50, unique=True, help_text="Category name should be max. of 50 characters")
code = models.CharField(max_length=10, unique=True, help_text="Province name should be max. of 10 characters")
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
ITEM_CATEGORY
class ItemCategoryHist(NowTimestampAndUserModel):
name = models.CharField(max_length=50, help_text="Category name should be max. of 50 characters")
code = models.CharField(max_length=10, help_text="Province name should be max. of 10 characters")
def __str__(self):
return self.name
我想将序列化器类设为
class StockSerializer(serializers.ModelSerializer):
item_name = Field(source='get_item_name')
class Meta:
model = PurchaseDetail
# some fields of PurchaseDetail
fields = ['id', 'item_name ', 'item_category']
def get_item_name(self, obj):
item_id = obj.item
item_obj = Item.objects.get(pk=item_id)
name = item_obj.name
return name
我只想使用采购明细序列化项目名称字段。我该怎么做?
答案 0 :(得分:0)
你需要的是序列化方法字段:https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
“item_name”字段可以是 SerializerMethodField,允许您使用自定义代码为该字段生成值。