3

如何在模型上创建动态字段?

假设我正在编写一个与股票市场相关的应用程序。我在某一天进行了购买,稍后我想根据今天的价格检查收益(或损失)。我会有这样的模型:

class Purchase(models.Model):
  ticker = models.CharField(max_length=5)
  date = models.DateField()
  price = models.DecimalField(max_digits=20, decimal_places=3)
  quantity = models.IntegerField()

我想做的是定义一个像这样的模型:

class PurchaseGain(Purchase):
  gain = models.DecimalField(max_digits=20, decimal_places=3)
  class Meta:
    proxy = True

这样我就可以这样做:

todays_price = get_price_from_webservice(ticker)
for p in PurchaseGain.objects.get_purchase_gain(todays_price):
  print '%s bought on %s for a gain of %s' % (p.ticker, p.date, p.gain)

其中 p.gain 是根据 get_purchase_gain 的输入动态计算的。我想使用模型而不只是即时构建字典,因为我想传递它并从实例中生成表单、保存更改等。

我尝试创建一个派生的 QuerySet,但这导致了循环依赖,因为 Purchase 需要了解 QuerySet(通过自定义管理器),并且 QuerySet 返回了一个迭代器,该迭代器需要实例化从 Purchase 派生的 PurchaseGain。

我有什么选择?

谢谢,克雷格

4

2 回答 2

2

为什么不在模型中添加gain()方法?

class Purchase(models.Model):
    ticker = models.CharField(max_length=5)
    date = models.DateField()
    price = models.DecimalField(max_digits=20, decimal_places=3)
    quantity = models.IntegerField()

    def gain(self, todays_price=None):
        if not todays_price:
            todays_price = get_price_from_webservice(self.ticker)
        result_gain = todays_price - self.price
        return result_gain

然后你几乎可以做你想做的事:

for p in Purchase.objects.all():
    print '%s bought on %s for a gain of %s' % (p.ticker, p.date, p.gain())
于 2012-05-31T07:24:54.610 回答
2

创建代理类让我感到困惑。通过向购买添加属性,我能够完成我想要的。

class PurchaseQuerySet(QuerySet):
  def __init__(self, *args, **kwargs):
    super(PurchaseQuerySet, self).__init__(*args, **kwargs)
    self.todays_price = None

  def get_with_todays_price(self, todays_price):
    self.todays_price = todays_price
    cloned = self.all()
    cloned.todays_price = todays_price
    return cloned

  def iterator(self):
    for p in super(PurchaseQuerySet, self).iterator():
      p.todays_price = self.todays_price
      yield p

class PurchaseManager(models.Manager):
  def get_query_set(self):
    return PurchaseQuerySet(self.model)

  def __getattr__(self, name)
    return getattr(self.get_query_set(), name)

class Purchase(models.Model):
  ticker = models.CharField(max_length=5)
  date = models.DateField()
  price = models.DecimalField(max_digits=20, decimal_places=3)
  quantity = models.IntegerField()

  objects = PurchaseManager()

  @property
  def gain(self):
    return self.todays_price - self.price

现在我可以这样做:

for p in Purchase.objects.filter(ticker=ticker).get_with_todays_price(100):
  print p
  print p.gain
于 2012-06-02T18:18:44.320 回答