Python 构造Django应用程序以将自定义业务规则附加到对象实例
我被如何构造代码以适应特定模型实例的特定业务规则所困扰 比如说。假设我有一个带有类型字段的联系人模型和Python 构造Django应用程序以将自定义业务规则附加到对象实例,python,django-models,Python,Django Models,我被如何构造代码以适应特定模型实例的特定业务规则所困扰 比如说。假设我有一个带有类型字段的联系人模型和choices=('I','Individual'),('C','Company))。根据我拥有的模型类型,我可能希望有自定义方法 所以大声想一想,像这样的事情会很好: class IndividualContact(Contact): """ A custom class used for Contact instances with type='I' """ criteria = Q
choices=('I','Individual'),('C','Company))
。根据我拥有的模型类型,我可能希望有自定义方法
所以大声想一想,像这样的事情会很好:
class IndividualContact(Contact):
""" A custom class used for Contact instances with type='I' """
criteria = Q(type='I')
# The goal here is that Contact is now aware of IndividualContact and constructs
# objects accordingly.
Contact.register(IndividualContact)
甚至:
class SpecialContact(Contact):
""" A custom class used for the contact with pk=1 """
criteria = Q(pk=1)
在这一点上,我有一个很好的家为我的特殊实例特定的代码
我探索的一种替代方法是使用模型继承,避免使用诸如类型字段之类的传递新行为的内容。这样,新类就可以优雅地插入到现有框架中,并且您可以很好地将自定义字段添加到不同的类型中,以备需要
在我的情况下,我在网站上有一个资源信用系统,允许我说“你可能只有2个列表和20张照片”。单独的资源类型是定量的,但是有一个通用的信用表,可以为各种内容类型提供信用。计算列表和照片的逻辑根据您使用的对象的类型而有所不同
即:
我目前的方法是使用单独的类,但我想简化这个样板文件,减少只使用
信用卡\u ptr\u id
创建N个单独表的必要性看看django代理模型。他们允许你做你想做的事
但是,因为在您的情况下,行为取决于字段值,所以您应该将自定义管理器添加到代理模型中,该模型仅检索查询中该类型的项
listing_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Listing), user=user, credit_amt=2)
# Should subtract **active** listings from current sum total of Listing credits.
listing_credit.credits_remaining()
photo_credit = Credit.objects.create(content_type=ContentType.objects.get_for_model(Photo), user=user, credit_amt=5)
# Photos have no concept of an active status, so we just subtract all photos from the current sum total of Listing credits.
# Also, the Photo might be associated to it's user through a 'created_by' field whereas
# Listing has a user field.
photo_credit.credits_remaining()