我尝试使用自定义命令向货币对象添加股票代码值,但我似乎无法将代码添加到CurrencyTickerSerializer
?我收到以下错误TypeError: 'QuerySet' object does not support item assignment
。我在一个特定的时间间隔内运行此命令,假设将股票代码添加到特定货币,但我想我需要添加一些内容才能将代码添加到TickerSerializer
中?
命令
class Command(BaseCommand):
def handle(self, *args, **options):
comparison='DKK'
url = 'URL'
page = requests.get(url)
data = page.json()
response_data = {}
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
currency['tickers'] = ticker
serializer = CurrencyTickerSerializer(data=currency)
if serializer.is_valid():
serializer.save()
串行
class TickerSerializer(serializers.HyperlinkedModelSerializer):
currency = serializers.PrimaryKeyRelatedField(many=False, queryset=Currency.objects.all())
class Meta:
model = Ticker
fields = ('currency', 'rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d',)
class CurrencyTickerSerializer(serializers.HyperlinkedModelSerializer):
tickers = TickerSerializer(many=True)
class Meta:
model = Currency
fields = ('id', 'name','symbol', '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 :(得分:2)
让我们检查您的代码在哪里出现此问题。
class Command(BaseCommand):
def handle(self, *args, **options):
comparison='DKK'
url = 'URL'
page = requests.get(url)
data = page.json()
response_data = {}
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
currency['tickers'] = ticker
serializer = CurrencyTickerSerializer(data=currency)
if serializer.is_valid():
serializer.save()
您的代码正常工作,直到currency['tickers'] = ticker
您将某个类视为array.use currency.tickers.add(ticker)
instate。它会起作用但不是你的情况,因为add函数会抱怨参数。它需要一个实例Ticker
类而不是json数据。所以知道
for ticker in data:
currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True)
if currency.exists():
tickers = Ticker(...)
currency.tickers.add(tickers)
serializer = CurrencyTickerSerializer(data=currency)