简体   繁体   English

Django在创建模型时出错

[英]Django error in creating model

I'm having an issue with creating a user profile with a foreign object. 我在创建带有异物的用户个人资料时遇到问题。

I have a user and I want to attach an account type to that user. 我有一个用户,我想将帐户类型附加到该用户。

model.py 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

The issue is I'm getting the below error: 问题是我遇到以下错误:

account = models.ForeignKey(Account, unique=True)
NameError: name 'Account' is not defined

How do I call the Account class for the foreign key? 如何调用外键的Account类?

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

You can use "app_name.Account" instead of Account . 您可以使用"app_name.Account"代替Account Replace app_name with the name of your app. app_name替换为您的应用名称。

As per John Gordon comment, I moved Account above UserProfile and it worked 根据约翰·戈登(John Gordon)的评论,我将“帐户”移到了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)

Thanks guys :) 多谢你们 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM