[Answered ]-Python/Django models

1đź‘Ť

âś…

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).

👤Burhan Khalid

1đź‘Ť

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”.

👤tobych

0đź‘Ť

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.

👤Qiang Jin

Leave a comment