我正在开发的应用程序是关于在线食品订单。餐馆老板在他/她的餐厅列出该餐厅提供的菜单。我为这种情况设计了模型。但我在我的评论模型中遇到问题,我收到NameError的错误:name' Restaurant'导入Restaurant类时未定义。
代码
餐馆/ models.py
class Restaurant(models.Model):
OPEN = 1
CLOSED = 2
OPENING_STATUS = (
(OPEN, 'open'),
(CLOSED, 'closed'),
)
owner = models.ForeignKey(User)
name = models.CharField(max_length=150, db_index=True)
slug = models.SlugField(max_length=150, db_index=True)
address = models.CharField(max_length=100)
city = models.CharField(max_length=100)
phone_number = models.PositiveIntegerField()
owner_email = models.EmailField()
opening_status = models.IntegerField(choices=OPENING_STATUS, default=OPEN)
website = models.URLField(max_length=300)
features = models.ManyToManyField(Choice, related_name="restaurants_features")
timings = models.ManyToManyField(Choice, related_name="restaurants_timings")
opening_from = models.TimeField()
opening_to = models.TimeField()
facebook_page = models.URLField(max_length=200)
twitter_handle = models.CharField(max_length=15, blank=True, null=True)
other_details = models.TextField()
# votes = models.IntegerField(choices=STARS, default=5)
class Menu(models.Model):
STARS = (
(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four'),
(5, 'five'),
)
menu_category = models.ForeignKey(Category, related_name="menu")
restaurant = models.ForeignKey(Restaurant)
name = models.CharField(max_length=120,db_index=True)
slug = models.SlugField(max_length=120,db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10,decimal_places=2)
stock = models.PositiveIntegerField()
vote = models.SmallIntegerField(choices=STARS, default=5)
查看/ models.py
from restaurants.models import Restaurant # I am getting an error here
class Review(models.Model):
STARS = (
(1, 'one'),
(2, 'two'),
(3, 'three'),
(4, 'four'),
(5, 'five'),
)
vote = models.SmallIntegerField(choices=STARS, default=5)
user = models.ForeignKey(User)
restaurant = models.ForeignKey(Restaurant)
review = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.vote
为什么我会收到这样的错误?
还有一个问题。餐厅有多种菜单。用户应该对每个菜单进行评分(仅评分无评论)。那么我的模型可以用于这样的功能吗?
答案 0 :(得分:0)
您可能有一个循环导入错误;模型文件试图互相导入,Python无法解决它。
请注意,如果您要做的只是定义关系,则无需导入实际模型;你可以使用字符串值代替。从review.models中删除导入,并在定义中执行此操作:
restaurant = models.ForeignKey('restaurant.Restaurant')
答案 1 :(得分:0)
您需要将餐馆的完整路径添加到系统路径
在review / models.py
中添加以下代码import sys
sys.path.append('<full path to parent dir of restaurants>')
from restaurants.models import Restaurant