如何在没有引用对象和实例的情况下获取集合名称?

2024-04-24 12:43:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个关于客户、产品和草稿的简单程序。你知道吗

因为它们以某种方式相互引用,所以当我删除一种类型的实体时,另一种类型的实体可能会出错。你知道吗

以下是我所拥有的:

你知道吗-客户.py你知道吗

class Customer(db.Model):
    """Defines the Customer entity or model."""
    c_name      = db.StringProperty(required=True)
    c_address   = db.StringProperty()
    c_email     = db.StringProperty() ...

你知道吗-草稿.py你知道吗

class Draft(db.Model):
    """Defines the draft entity or model."""
    d_customer      = db.ReferenceProperty( customer.Customer,
                                        collection_name='draft_set')
    d_address       = db.StringProperty()
    d_country       = db.StringProperty() ...

好的,现在我要做的是,在删除客户之前,检查客户是否有任何引用他的草稿。 这是我使用的代码:

def deleteCustomer(self, customer_key):
    '''Deletes an existing Customer'''

    # Get the customer by its key
    customer = Customer.get(customer_key)

    if customer.draft_set: # (or customer.draft_set.count > 0...)
        customer.delete()

    else:
        do_something_else()

现在,问题来了。 如果我有一个草案,以前与选定的客户在它创建,没有任何问题,它做什么必须做的。但是,如果我没有创建任何引用该客户的草稿,在尝试删除该客户时,它将显示以下错误:

AttributeError: 'Customer' object has no attribute 'draft_set'

我做错什么了?是否需要始终创建包含客户的草稿,以便让collection\u name属性“可用”?你知道吗

编辑:我发现了错误所在。 由于这两个类在不同的.py文件中,GAE似乎在“遍历”包含该模型的文件的同时将实体加载到数据存储中。 因此,如果我正在执行程序,并且从未使用或导入该文件,则数据存储在此之前不会更新。 现在我要做的是:

from draft.py import Draft

在de“deleteCustomer()”函数中,它终于可以正常工作了,但是我得到了一个可怕的“警告没有使用”,因为这样。你知道吗

我还有别的办法可以解决这个问题吗?你知道吗


Tags: or文件thekeynamepy实体db
2条回答

有两种可能的解决办法:

  1. 丑陋,糟糕的一个:正如我编辑的问题所描述的。

  2. 最佳实践:将所有模型放在一个文件中(例如。型号.py)看起来是这样的:

    class Customer(db.Model):
    
        """Defines the Customer entity or model."""
    
        c_name      = db.StringProperty(required=True)
        c_address   = db.StringProperty()
        c_email     = db.StringProperty() ...
    
    class Draft(db.Model):
    
        """Defines the draft entity or model."""
        d_customer      = db.ReferenceProperty( customer.Customer,
                                    collection_name='draft_set')
        d_address       = db.StringProperty()
        d_country       = db.StringProperty() ...
    

放轻松!你知道吗

集合名称属性是一个查询,因此它应该始终可用。你知道吗

您可能缺少的是reference_class参数(请检查ReferenceProperty docs

class Draft(db.Model):
"""Defines the draft entity or model."""
    d_customer = db.ReferenceProperty(reference_class=customer.Customer, collection_name='draft_set')

以下应起作用:

if customer.draft_set.count():
    customer.delete()

请注意,customer.draft_set将始终返回true,因为它是生成的查询对象,因此必须使用count()

相关问题 更多 >