1

I have the following model in django:

class Node(models.Model):
    name = models.CharField(max_length=255)

And this subclass of the above model:

class Thingy(Node):
    name       = models.CharField(max_length=100)
    otherstuff = models.CharField(max_length=255)

The problem with this setup is that while everything Just Works, a look into the database shows that syncdb has created two tables. One called appname_node with a column called name and another one called appname_thingy with two columns: name and otherstuff. When a new object is created, the name value is copied into both tables... not really cool if you dig the whole concept of normalisation :-)

Can someone explain to me how I might modify the max_length value of the "name" property in "Thingy" without re-defining it?

1 Answer 1

3

Your implementation is totally wrong, that is not how you suppose to write parent and child class. either define name in parent class or child class, if you define it in a parent class then you can't define again in the child because new field will be created instead. so if you want to change max_length in the child, then I would recommend that you declare name in the child so that any class that inherits from node will set its own name with its own max_length.

the correct implementation is

class Node(models.Model):
    #other class attributes

child class should inherit parent attributes and add its own stuff.

class Thingy(Node):
    name       = models.CharField(max_length=100)
    otherstuff = models.CharField(max_length=255)

now when you query, you only get one name instead of the two.

3
  • Mohamed is correct. Read docs.djangoproject.com/en/dev/topics/db/models/#id5. Depending on the specifics of your problem, you might want to consider using Abstract Base Classes as opposed to true Multi-Table Inheritance. Dec 19, 2009 at 0:39
  • Sorry, I kept some stuff out of there to simplify the question -- for starters, the parent model can't be abstract because it has foreign key constraints in it. As for changing the max_length in the child while keeping the property in the parent, are you two telling me that Django doesn't support overriding the attributes of a property from a parent? The "name" value needs to stay in the parent. It's common in all of the child models and there are too many other shared properties that must exist in this child. If I can't change this attribute, I'll have to basically copy "node" :-( Dec 19, 2009 at 1:35
  • Yes, django treats each model class as a database table.
    – Mohamed
    Dec 19, 2009 at 2:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.