【问题标题】:How to create dynamically generated value in PeeWee model?如何在 PeeWee 模型中创建动态生成的值?
【发布时间】:2018-12-27 21:14:55
【问题描述】:

在我目前使用的 ORM 中,有一个选项可以向模型添加一个值(字段?),该值不存储在数据库中,而是使用其他值构建。

下面是一个简单的例子:

class MediaFile(BaseModel):
    ID = IntegerField()
    FileName = str(ID) + ".jpg"

所以ID 存储在数据库中,FileNameID 构造而成。上面的例子当然不适用于 PeeWee,因为 IDIntegerField,而不是 int 我需要。

我怎样才能在 PeeWee 中做这样的事情?怎么称呼?

【问题讨论】:

    标签: python peewee


    【解决方案1】:

    好吧,如果您只想访问一个存储在数据库中的属性,请记住 peewee 模型只是 Python 类:

    class MediaFile(BaseModel):
        ID = AutoField()  # You should probably use this for auto-inc IDs.
    
        @property
        def FileName(self):
            return str(self.ID) + '.jpg'
    

    对于您希望能够将其用作 SQL 构造和计算实例值的更复杂的操作,请参阅hybrid properties。使用混合属性的示例:

    class Interval(Model):
        start = IntegerField()
        end = IntegerField()
    
        @hybrid_property
        def length(self):
            return self.end - self.start
    
        @hybrid_method
        def contains(self, point):
            return (self.start <= point) & (point < self.end)
    

    通过这种混合属性和混合方法,我们可以在 SQL 查询中在模型实例上使用这些属性。所以我们最终能够做以下事情:

    query = Interval.select().where(Interval.contains(2))
    

    将生成以下 SQL:

    SELECT "id", "start", "end"
    FROM "interval" AS t1
    WHERE (("start" <= 2) AND (2 < "end"))
    

    但我们也可以这样做:

    obj = Interval(start=1, end=10)
    obj.contains(2)  # returns True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 2013-01-05
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2023-01-31
      • 1970-01-01
      相关资源
      最近更新 更多