Django响应嵌套模型

时间:2017-04-10 10:42:25

标签: django django-models django-rest-framework django-serializer django-request

我有以下型号:

class Asset(models.Model):
    isin = models.CharField(max_length=100)
    asset_type = models.CharField(max_length=50)
    last_price = models.FloatField
    security_weight = models.FloatField
    update_date = models.DateTimeField

    def __str__(self):
        return self.isin

    class Meta:
        ordering = ('isin',)

class PortfolioElement(models.Model):
    nominal = models.FloatField
    weight = models.FloatField
    asset = models.OneToOneField(
        Asset,
        on_delete=models.CASCADE,
        primary_key=True,
    )

    def __str__(self):
        return self.asset.isin

    class Meta:
        ordering = ('asset',)

class Portfolio(models.Model):
    number = models.CharField(max_length=100)
    update_date = models.DateTimeField
    elements = models.ManyToManyField(PortfolioElement)

    def __str__(self):
        return self.number

    class Meta:
        ordering = ('number',)

class Client(models.Model):
    number = models.CharField(max_length=100)
    update_date = models.DateTimeField
    portfolios = models.ManyToManyField(Portfolio)

    def __str__(self):
        return self.number

    class Meta:
        ordering = ('number',)

以及以下序列化程序:

class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = ('number', 'portfolios')
        depth = 1

但是,我希望看到投资组合(和投资组合元素)中的实际数据。但是当我尝试在任意客户端上发出GET请求时(通过(Client).number字段)我只能看到以下内容:

{
"number": "28101317",
"portfolios": [
    {
        "id": 14,
        "number": "5471-339425",
        "elements": [
            {
                "asset": 326
            },
            {
                "asset": 327
            }, ... (and so on)

如何调整我的代码,以便我也能获得实际的“资产”信息?

/尼克拉斯

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

$CI->db->select('UserID, Email, Alias, Status, Age');
$CI->db->from('Users');
$CI->db->where('Status', 'Available');
$query = $CI->db->get();
$result = $query->result();
//next comes a function that sends $result to the client app