Skip to main content
 首页 » 编程设计

python之Django:向模型类对象添加附加属性

2025年05月04日20del

这是使用 Google App Engine。我不确定这是否适用于普通的 Django 开发,或者 Google App Engine 是否会发挥作用。如果是,请告诉我,以便我更新此问题的描述。

class MessageModel(db.Model): 
    to_user_id = db.IntegerProperty() 
    to_user = db.StringProperty(multiline=False) 
    message = db.StringProperty(multiline=False) 
    date_created = db.DateTimeProperty(auto_now_add=True) 

现在,当我执行查询获取“MessageModel”列表并将其发送到 template.html 以进行绑定(bind)时,我想包含更多属性,例如“since_date_created”以输出多久以前最后一个输出,可能会使用 message 属性并添加其他有助于布局的参数,例如“highlight”、“background-color”等...

我想到的唯一方法是遍历初始查询对象并创建一个新列表,我将在其中添加属性值,然后将其追加回列表。

    for msg in messagesSQL: 
    msg.lalaland = "test" 
            msg.since_created_time = 321932 
            msglist.append(msg) 

然后不再传递 template.html messagesSQL,而是传递 msglist。

请您参考如下方法:

在通过 for 循环向模板添加元素后,您应该仍然能够将它的 messagesSQL 发送到模板。 Python 允许这样的事情。

在某些情况下可能有意义的其他事情是提供您的 MessageModel 方法。例如,如果您有一个

def since_date_created(self): 
    '''Compute the time since creation time based on self.date_created.''' 

然后(假设模板中有“messagesSQL”),您可以将函数用作

{% for msg in messagesSQL %} 
    {{ msg.since_date_created }} 
{% endfor %} 

基本上,您可以调用模型中的任何方法,只要它不需要传递给它的参数即可。