我有两个django模型
模型A
class B(models.Model):
bname = models.CharField(max_length=64, verbose_name='name')
mod = models.ForeignKey(A, related_name='a_b',null=True,on_delete=models.CASCADE)
和模型B
class BSerializer(serializers.ModelSerializer):
mod= ASerializer(many=False, read_only=True)
class Meta:
model = B
fields = (','id','bname','mod.aname')
模型B的序列化器是
mod.aname
我希望使用模型B的序列化程序访问模型A的 aname 字段。使用mod.aname不起作用。它说
字段名
B
对模型INSERT INTO PAYMENT ( OWNER_HI, ACCOUNT_ID, DATE_PAYMENT, ACCOUNT_VALUE_BEFORE, CURRENCY,EXCHANGE_RATE, SUM, SUM_USD, DATE_INPUT, OPERATOR_ID, DOCUMENT, INVOICE_ID) VALUES ( OWNER, ID, TO_CHAR(SYSDATE, 'YYYY-MM-DD'), (SELECT VALUE FROM ACCOUNT WHERE ACCOUNT_ID = 386), (SELECT CURRENCY_IDCURRENCY_ID FROM CURRENCY_EXCHANGE WHERE rownum=1 ORDER BY CURRENCY_ID DESC), (SELECT EXCHANGE_RATE FROM CURRENCY_EXCHANGE WHERE rownum=1 ORDER BY CURRENCY_ID DESC), 50, (50 * RATE), TODAY, 386, 'teste sis', null);
无效。
我该怎么做?
答案 0 :(得分:2)
这个怎么样?在source
内使用参数serializers.CharField
:
class BSerializer(serializers.ModelSerializer):
mod = serializers.CharField(
source='mod.aname',
read_only=True
)
class Meta:
model = B
fields = ('id','bname','mod')
答案 1 :(得分:0)
在将相关模型的字段引用为字符串时使用两个下划线,例如'mod__aname'
。
class HotelSerializer(serializers.ModelSerializer):
mod= ASerializer(many=False, read_only=True)
class Meta:
model = Hotel
fields = ('id','bname','mod__aname')
如果ASerializer
看起来像这样,这应该有效:
class ASerializer(serializers.ModelSerializer):
class Meta:
model = A
fields = '__all__'