0

我似乎无法使用 Django 设置实例变量。

我想要发生的是:

a,b = User(), User()
a.set_status('abc')
b.set_status('def')
b.get_status()
>>> 'def'
a.get_status()
>>> 'abc'

不幸的是,不断发生的事情是:

a,b = User(), User()
a.set_status('abc')
b.set_status('def')
b.get_status()
>>> 'def'
a.get_status()
>>> 'def'

我相信这是因为status变量是类变量而不是实例变量。如何使代码表现得像我想要的那样?我的模型如下。

class Status(models.Model):

    def __init__(self, status = '', time=datetime.datetime.min, *args, **kwargs):
        self.status = status
        self.status_time = time
        super(Status, self).__init__(*args, **kwargs)

    def set_status(self, s):
        self.status = s
        self.status_time = datetime.datetime.now()
        self.save()
    def get_status(self):
        now = datetime.datetime.now()
        if now-self.status_time<datetime.timedelta(minutes=15):
            return self.status
        return None


class User(models.Model):
    facebook_id = models.CharField(max_length=200)
    friends = ListField()
    status = Status()

    @classmethod
    def create_user(cls, fid, friends):
        k = User()
        k.facebook_id = fid
        k.friends = friends
        k.status = Status()
        k.status.save()
        k.save()

    def login(self, facebook_friends):
        self.friends = facebook_friends
        self.save()

    def set_status(self, status):
        self.status.set_status(status)
        #return matching statuses

    def get_status(self):
        return self.status.get_status()
4

1 回答 1

1

您的status属性是global。它是类的一部分,而User不是实际实例的一部分。所以这实际上是正常的行为。set_status()将通过. status_Userget_status()

You should redesign your model. You don't really need the Status class anyway. You can have that business logic directly in your User methods set_status and get_status. But if you need to keep track of every status change then just have a ForeignKey to a Status model.

于 2013-03-29T19:39:54.850 回答