Django模型字段替代名称

时间:2018-10-11 18:09:54

标签: django django-models

我有一个存储API响应的模型。我想传递一个包含响应以更新模型的字典。

from ua in db.FooBar_UserAuth
join ra in db.FooBar_RoomAuth
    on new { ua.FooBar_Authorization.AuthId, IsActive = true }
    equals new { ra.AuthId, ra.IsActive } into raJoin
from ra in raJoin.DefaultIfEmpty()
join ri in db.Room_Inventory
    on new { ra.RmId, IsActive = true }
    equals new { RmId = ri.RMID, ri.IsActive } into riJoin
from ri in riJoin.DefaultIfEmpty()
where
    ua.FooBar_Authorization.IsActive &&
    ua.IsPi == true &&
    ua.FooBar_User.IsActive &&
    ua.FooBar_User.UserId == 10
group new { ua.FooBar_Authorization, ua.FooBar_Authorization.FooBar_AuthType, ra } by new
{
    AuthId = (int?)ua.FooBar_Authorization.AuthId,
    ua.FooBar_Authorization.FooBar_AuthType.AuthTypeAbbr,
    ua.FooBar_Authorization.ExpirationDate
} into g
select new
{
    AuthId = g.Key.AuthId.Value,
    RmCnt = g.Count(p => p.ra != null),
    AuthType = g.Key.AuthTypeAbbr,
    ExpirationDate = g.Key.ExpirationDate
}

但API响应格式如下:

class Currency_Trending_Info(models.Model):
    """Stores a market's last price as well as other stats based on a 24-hour sliding window."""

    crypto_currency = models.ForeignKey(Crypto_Currency, on_delete=models.CASCADE)
    market = models.CharField(max_length=30, blank=True, null=False)
    last_volume = models.DecimalField(max_digits=18, decimal_places=9)
    last_volume_to = models.DecimalField(max_digits=18, decimal_places=9)
    last_trade_id = models.BigIntegerField()
    ...
    ...

所以我的问题是有一种方法来定义字段的替代名称,还是我应该更改模型字段以对应API响应,例如{ ... 'TYPE':'5', 'MARKET':'CCCAGG', 'FROMSYMBOL':'BTC', 'TOSYMBOL':'USD', 'FLAGS':'4', 'PRICE':6276.14, 'LASTUPDATE':1539279469, 'LASTVOLUME':0.03845327, 'LASTVOLUMETO':239.21394734299997, 'LASTTRADEID':'52275450' ... } (当然也可以使用lastvolume = models.DecimalField(max_digits=18, decimal_places=9)将密钥转换为小写字符串。)

欢迎任何建议

编辑: 保存到数据库

key.lower()

1 个答案:

答案 0 :(得分:0)

一种方法是重写model.save方法以在保存对象时执行自定义任务。您可以从那里手动为每个字段分配值并保存。请参考http://books.agiliq.com/projects/django-admin-cookbook/en/latest/override_save.htmlofficial doc

它看起来像这样:

class Crypto(models.Model):
...
   def save(self, *args, **kwargs):
       self.attribte_name = kwargs['value']
       super(Model, self).save(*args, **kwargs)

别忘了叫super。因为如果您错过了,db不会改变。