JosephConrad
JosephConrad

Reputation: 688

Python/Django models

I am fairly new to Python/Django. What I would like to do is to store descriptions of cars separately, but simultaneously I would like to label (in django admin) car description like this:

class CarDescription(models.Model):

    length = models.IntegerField(max_length=10)
    def __unicode__(self):
        return "description of the car no %d" % (Car.id)


class Car(models.Model):

    description = models.OneToOneField(CarDescription)

I know that Car.id is wrong there (circular reference). Is there any way to solve it?

Upvotes: 1

Views: 394

Answers (3)

Qiang Jin
Qiang Jin

Reputation: 4467

You can check django's document, https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-one-relationships.

As addressed in the doc, you can access one to one fields directly,

class CarDescription(models.Model):

    length = models.IntegerField(max_length=10)
    def __unicode__(self):
        return "description of the car no %d" % (self.car.id)

It works only both car and car description instances exists, or else exception will be thrown.

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174614

You should structure your models like this:

class Car(models.Model):

    # everything that has to do _only_ with a car

class CarDescription(models.Model):

    car = models.ForeignKey(Car) # each description can belong to only one car
    length = models.IntegerField(max_length=10)
    # other fields that have only to do with a description

    def __unicode__(self):
        return unicode("description of the car no %d" % (self.car.pk))

Django has a very nice API for looking up related objects which you should go through (once you have finished the tutorial).

Upvotes: 1

tobych
tobych

Reputation: 2961

All you need is:

class Car(models.Model):

    description = models.CharField(max_length=20)

Done. More fields are fine. You're overcomplicating things otherwise.

You need to study what's called "relational modeling".

What you're doing is "premature optimization" and probably "pessimization".

Upvotes: 1

Related Questions