我是Django的新手,所以我刚刚编写了一个项目来了解它,但我对这段代码有点问题,我希望能够作为汽车对象,如果它可用,所以我做一个:
>>>cars = Car.objects.all()
>>>print cars[0].category
>>>'A'
>>>cars[0].available(fr, to)
导致a:
>>>global name 'category' is not defined
所以看来我无法访问类中的self.category,有什么想法吗?
from django.db import models
class Car(models.Model):
TRANSMISSION_CHOICES = (
('M', 'Manual'),
('A', 'Automatic'),
)
category = models.CharField("Category",max_length=1,primary_key=True)
description = models.CharField("Description",max_length=200)
numberOfCars = models.IntegerField("Number of cars")
numberOfDoors = models.IntegerField("Number of doors")
transmission = models.CharField("Transmission", max_length=1, choices=TRANSMISSION_CHOICES)
passengers = models.IntegerField("Number of passengers")
image = models.ImageField("Image", upload_to="photos/%Y/%m/%d")
def available(self, fr, to):
rents = Rent.objects.filter(car=self.category)
rents = rents.excludes(start < fr)
rents = rents.exclude(end > to)
return cont(rents)
def __unicode__(self):
return "Class " + self.category
class Rent(models.Model):
car = models.ForeignKey(Car)
start = models.DateTimeField()
end = models.DateTimeField()
childrenSeat = models.BooleanField()
extraDriver = models.BooleanField()
def __unicode__(self):
return str(self.car) + " From: " + str(self.start) + " To: " + str(self.end)
答案 0 :(得分:0)
虽然我无法看到您所遇到的错误与之相关,但您使用的过滤器看起来并不正确。
您可以在Car模型中将类别定义为字符串:
category = models.CharField("Category",max_length=1,primary_key=True)
在租借模式中将汽车定义为外键:
car = models.ForeignKey(Car)
然后你尝试过滤租金:
rents = Rent.objects.filter(car=self.category)
但汽车应该是这里的典范,而不是charfield。也许你的意思是说car = self?