我在两个模型之间从多个关系返回数据时遇到了麻烦。我不想显示所有Currency? objects with their newest
Ticker object related to that currency based on the
created_at`字段。我想知道如何在json中创建这样的输出?
所需的输出
[
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"img": "/media/static/img/currencies/bitcoin_uzSOQkH.png",
"tickers":
{
"rank": 1,
"price_dkk": "111239.222648",
"market_cap_dkk": 1861795518438,
"percent_change_1h": "0.03",
"percent_change_24h": "2.44",
"percent_change_7d": "46.80",
"created_at": "2017-12-12T20:11:49.995851Z"
}
}
]
查看
class CurrencyGetView(ProtectedResourceView):
def get(self, request):
currencies = CurrencySerializer(Currency.objects.all(), many=True)
return JsonResponse(currencies.data, safe=False)
串行
class TickerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Ticker
fields = ('rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d', 'created_at', )
class CurrencySerializer(serializers.HyperlinkedModelSerializer):
tickers = TickerSerializer(many=True)
class Meta:
model = Currency
fields = ('id', 'name','symbol', 'img', 'tickers',)
模型
class Ticker(models.Model):
rank = models.IntegerField()
price_dkk = models.DecimalField(max_digits=20, decimal_places=6)
market_cap_dkk = models.BigIntegerField()
percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2)
percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = _('Ticker')
def __str__(self):
return self.id
class Currency(models.Model):
symbol = models.CharField(max_length=4, default='BTC', unique=True)
name = models.CharField(max_length=20, default='Bitcoin', unique=True)
img = models.ImageField(upload_to = 'static/img/currencies', blank=True)
is_active = models.BooleanField(default=False)
tickers = models.ManyToManyField(Ticker)
class Meta:
verbose_name_plural = 'currencies'
def __str__(self):
return self.name
答案 0 :(得分:1)
认为这样的事情会起作用,当前实现的问题是many=True
将得到所有相关的代码并将这些对象返回到列表中,这是正确的行为,但是因为你只想显示您仅需要序列化最新对象所需的每种货币的最新股票代码。
class CurrencySerializer(serializers.HyperlinkedModelSerializer):
tickers = serializers.SerializerMethodField()
class Meta:
model = Currency
fields = ('id', 'name','symbol', 'img', 'tickers')
def get_tickers(self, obj):
data = {}
try:
latest_ticker = obj.tickers.latest('-created_at')
data = TickerSerializer(instance=latest_ticker).data
except Ticker.DoesNotExist:
pass
return data
答案 1 :(得分:1)
我认为这应该在查询级别上解决,最好是prefetch_related
。但是Django can't slice Prefetch objects。游民。 Subquery非常缓慢。
我能想到的最佳解决方案是创建SerializerMethodField,使用切片数据集调用TickerSerializer
。缺点是DRF将为列表中的每个Currency
对象触发一个额外的SQL查询。
from rest_framework.fields import SerializerMethodField
class CurrencySerializer(serializers.HyperlinkedModelSerializer):
ticker = SerializerMethodField()
def get_ticker(self, obj):
return TickerSerializer(
instance=obj.tickers.order_by('-created_at')[:1],
many=True
).data
class Meta:
model = Currency
fields = ('id', 'name','symbol', 'img', 'tickers', 'ticker')