文章
问答
冒泡
DjangoRESTFramework序列化外键获取外键的值方法
##### model.py
class A(models.Model):
    name = models.CharField(max_length=25, blank=True, null=True)
    size = models.CharField(max_length=25, blank=True, null=True)

class B(models.Model):
    name = models.CharField(max_length=25, blank=True, null=True)
    location = models.CharField(max_length=25, blank=True, null=True)
    a = models.ForeignKey(A, on_delete=models.CASCADE, blank=True, null=True)
    
    class Meta:
        db_table = "table_b"
    
    @property
    def a(self):
        return {"name": self.a.name, "size": self.a.size}

### serializers.py
class BSerializers(serializers.ModelSerializer):
    a = serializers.ReadOnlyField()

    class Meta:
        model = EmployerProfile
        fields = ["name", "location", "a"]


####返回结果####
{
    name: "",
    location: "",
    a: {
        name: "",
        size: "",
    }
}
python

关于作者

zhyim
学海无涯,回头是岸
获得点赞
文章被阅读