views:

134

answers:

1

I'm new to Django so I just made up an project to get to know it but I'm having a little problem with this code, I want to be able to as the car obj if it is available so I do a:

>>>cars = Car.objects.all()
>>>print cars[0].category
>>>'A'
>>>cars[0].available(fr, to)

that results in a:

>>>global name 'category' is not defined

So it seems that I don't have access to the self.category within the class, any ideas?

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)
A: 

Although I can't see how the error you are getting relates to it, the filter you are using doesn't look correct.

You define category as a string in the Car model:

category = models.CharField("Category",max_length=1,primary_key=True)

And define car as a foreignkey in the Rent model:

car = models.ForeignKey(Car)

And then you try and filter Rents:

rents = Rent.objects.filter(car=self.category)

But car should be a model here, not a charfield. Perhaps you meant to say car=self?

Andre Miller
Thanks. I realized what my issue was, i was running "python manage.py shell" and I thought it was enough to re-import my package after I made a change to it. I was dead wrong. As soon as I quit the shell and did this allover again my code got updated and the error went away. Thanks for the tip on car=self, car=self.category was my db oriented thinking :)
davideagle
Using QuerySets there are also other ways of getting the data you want. For example, since there is a foreignkey, you can use rents = self.rent_set
Andre Miller