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?
-
1Why would you want to store it separately, if there is 1-to-1 relationship? It will make your life harder with no benefits.Andrey– Andrey2013年03月24日 00:54:01 +00:00Commented Mar 24, 2013 at 0:54
-
Well, I would like to split it, because it can have potentially many fields. I would prefer to have two entities with smaller amount of attributes rather than one with many attributes.JosephConrad– JosephConrad2013年03月24日 00:57:20 +00:00Commented Mar 24, 2013 at 0:57
-
what is your reasoning behind it? You have to have real good reasons for such insane normalization.Andrey– Andrey2013年03月24日 01:00:01 +00:00Commented Mar 24, 2013 at 1:00
-
ok, if you want it THAT much, just add string field to CarDescription and that's it. But seriously, I doubt it is reasonable.Andrey– Andrey2013年03月24日 01:01:01 +00:00Commented Mar 24, 2013 at 1:01
-
Ok, so you suggest to split class only in case of some kind of inheritance? And generally not to introduce one-to-one relation?JosephConrad– JosephConrad2013年03月24日 01:11:39 +00:00Commented Mar 24, 2013 at 1:11
3 Answers 3
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).
Comments
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".
Comments
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.