Django模型实例特定代码 [英] Django model instance specific code

查看:103
本文介绍了Django模型实例特定代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个Django模型中,我必须为每个模型实例添加特定的代码。现在,我想知道什么是实现这个的好方法。我目前的尝试导致一个很大的,难以阅读的if语句。

in one of my Django models I have to add specific code for each model instance. Now, I wonder what would be a good way to implement this. My current attempt results in a big, hard to read if statement.

考虑以下模型:

class Foo(models.Model):
    name = models.CharField(max_length=255)

    def do_instance_specific_stuff(self, arg):
        if self.id == 1:
            do_X(arg)
        elif self.id == 2:
            do_Y(arg)
        else:
            do_Z()

现在,有大约20个模型实例的自定义代码,它将保持在这个数量级。任何想法或模式如何以干净,可读的方式实现?

Right now, there is custom code for around 20 model instances and it will stay in this magnitude. Any ideas or patterns how this can be implemented in a clean, readable way?

感谢任何帮助。

推荐答案

我将添加另一个字段到您的模型,供应商。然后将每个供应商的方法添加到您的模型中,并使用getattr调用它们:

I would add another field to your model, vendor. Then add per-vendor methods to your model, and invoke them with getattr:

class Foo(models.Model):
    name = models.CharField(max_length=255)
    vendor = models.CharField(max_length=50)

    def vendor_fedex(self, arg):
        blah blah

    def vendor_ups(self, arg):
        blah blah

    def vendor_usps(self, arg):
        blah blah

    def do_instance_specific_stuff(self, arg):
        fn = getattr(self, "vendor_"+self.vendor, None)
        if not fn:
            raise Exception("Uh-oh, bad vendor")
        fn(arg)

根据 id 似乎非常脆弱。在您的数据模型中,每个供应商字符串只会显示一次,但它将是可读性和可延展性。如果 getattr 找不到供应商代码,您可以决定要做什么。

Depending on particular values of id seems very fragile. In your data model, each vendor string will appear only once, but it will be readable and malleable. You can decide what you want to do if the getattr can't find the vendor code.

这篇关于Django模型实例特定代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆