Django:从外键模型的字段填充序列化字段

2024-09-26 18:03:24 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有3个模型:

class MeterialPricing(models.Model):
    list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    book_pricing = models.ForeignKey('books.BookPricing', null=True, blank=True)
    inventory_pricing = models.ForeignKey('store.InventoryPricing', null=True, blank=True)

class BookPricing(models.Model):
    list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)

class InventoryPricing(models.Model):
    list_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)

和序列化程序类:

class MaterialPricingSerializer(ModelSerializer):
    class Meta:
        model = MaterialPricingShell
        fields = ('pk', 'list_price',)

如您所见,现在,序列化的列表价格来自MaterialPricing模型

如果存在BookPricing或InventoryPricinglist\u price,我想将序列化的list\u price设置为其中之一。BookPricing中的标价优先级最高,然后是InventoryPricing,如果两者都为空,那么我们可以让标价成为MeterialPricing模型中的标价

我正在研究使用SerializerMethodField(),但我不确定是否有某种post钩子来查看BookPricing或InventoryPricing模型上是否存在标价


Tags: 模型truemodelmodelsnullpricemaxlist

热门问题