将附加信息附加到模型实例djang

2024-09-21 03:21:53 发布

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

我有一个django模型,我想根据实例所在的环境(用户登录的环境)附加一条额外的信息。出于这个原因,我不想在数据库级别进行

这样可以吗?还是有我没有预见到的问题

在models.py中

class FooOrBar(models.Model):
    """Type is 'foo' or 'bar'
    """
    def __init__(self, type):
        self.type = type

在views.py中

class FooCheck(FooOrBar):
    """Never saved to the database
    """
    def __init__(self, foo_or_bar):
        self.__dict__ = foo_or_bar.__dict__.copy()

    def check_type(self, external_type):
        if external_type == 'foo':
            self.is_foo = True
        else:
            self.is_foo = False


foos_or_bars = FooOrBar.objects.all()
foochecks = map(FooCheck, foos_or_bars)
for foocheck in foochecks:
    foocheck.check_type('foo')

额外的信用问题:有没有一种更有效的方法来调用多个对象上的一个方法,即用聪明的东西替换最后一个forloop


Tags: orpyself环境fooinitismodels
2条回答

好吧,这样不行。试图删除FooOrBar对象会引发对

OperationalError at /

no such table: test_FooCheck

为了避免这个问题,我不打算继承FooOrBar的遗产,但如果有人对更好的方法有什么建议,我会很感兴趣的

我也有类似的问题,我做了一些类似的事情:

class Foo(models.Model):
    # specific info goes here

class Bar(models.Model):
    # specific info goes here

class FooBar(models.Model):
    CLASS_TYPES = {
        "foo":Foo,
        "bar":Bar
    }
    type = models.CharField(choices=CLASS_TYPES)
    id = models.IntegerField()

    #field to identify FooBar

然后你可以使用

object = FooBar.CLASS_TYPES[instance.type].objects.get(id=instance.id)

其中instance是FooBar实例

相关问题 更多 >

    热门问题