我在使用外来对象创建用户个人资料时遇到问题。
我有一个用户,我想将帐户类型附加到该用户。
model.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
account = models.ForeignKey(Account, unique=True)
class Account(models.Model):
reports = models.IntegerField(default=3)
accounttype = models.CharField(default='Free', max_length=250)
description = models.CharField(default='N/A', max_length=250)
monthlycost = models.FloatField(default=0.0)
def __str__(self):
return self.user.username + " - " + self.accounttype
问题是我收到以下错误:
account = models.ForeignKey(Account, unique=True)
NameError: name 'Account' is not defined
如何为外键调用Account类?
答案 0 :(得分:1)
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
account = models.ForeignKey("app_name.Account", unique=True)
class Account(models.Model):
reports = models.IntegerField(default=3)
accounttype = models.CharField(default='Free', max_length=250)
description = models.CharField(default='N/A', max_length=250)
monthlycost = models.FloatField(default=0.0)
def __str__(self):
return self.user.username + " - " + self.accounttype
您可以使用"app_name.Account"
代替Account
。将app_name
替换为您应用的名称。
答案 1 :(得分:0)
根据John Gordon的评论,我将Account移到了UserProfile之上并且有效
class Account(models.Model):
reports = models.IntegerField(default=3)
accounttype = models.CharField(default='Free', max_length=250)
description = models.CharField(default='N/A', max_length=250)
monthlycost = models.FloatField(default=0.0)
def __str__(self):
return self.user.username + " - " + self.accounttype
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
account = models.ForeignKey(Account, unique=True)
谢谢你们:)