2

我正在尝试扩展我的模型以包含 User 但运气不佳。

from django.db import models
from django.contrib.auth.models import User

class TestModel(models.Model):
    user = models.OneToOneField(User)

    def __unicode__(self):
        return "Value[" + self.user + "];"

但是,当我尝试对此进行测试时,我得到以下信息:

>>> t = TestModel()
>>> t
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 373, in __repr__
    u = unicode(self)
  File "/Users/lkatz/tmp/private/Projects/Web/rcos_portal/driver/models.py", line 39, in __unicode__
    return "Value[" + self.user + "];"
  File "/Library/Python/2.7/site-packages/django/db/models/fields/related.py", line 343, in __get__
    raise self.field.rel.to.DoesNotExist
DoesNotExist
4

1 回答 1

2

您没有将 User 实例传递给您的类 TestModel:

做这样的事情:

from django.contrib.auth.models import User

us = User.objects.all()[0]
t = TestModel(user=us)
t.save()
print t
于 2012-11-17T22:30:47.840 回答