开发者

How do I make changes to a model in Django?

How does Django handle changes to my Model? Or, what help does it offer me to do this?

I am thinking of a situation where I have already have published data to my DB which I don't want to lose, but I need to make changes to my data model - for example, adding extra fields to a particular class, changing the t开发者_开发技巧ypes of fields, etc. My understanding is that syncdb won't ever alter tables that already exist in the DB.

For example, let's say I have the following model:

class Person(models.Model):
    name = models.CharField(max_length=200)
    phone_number=models.CharField(max_length=200)
    hair_colour=CharField(max_length=50)

Things I might want to do to Person off the top of my head:

  1. I wish to add an 'age' field.
  2. I realise I want to use IntegerField instead of CharField for phone_number (whether this is a good idea or not, is out of scope...) - assuming it's possible.
  3. I realise that I no longer wish to define hair_colour 'inline' within Person, because several people share the same hair colour - I wish instead to change this to be a foreign key to some other model.

Whilst I can imagine some of these are tough/impossible for the framework to 'guess' exactly what needs to be done to my data if all I do is update the models.py, I can imagine that there might still be some tooling to help enable it - does it exist?

In particular I imagine there must be some good patterns for option 1.

I'm very new to Django and have no experience with any other ORM-type stuff, which I think this is - I've always been a bit suspicious of ORMs, mainly for the reasons above :)


Django itself will not attempt to modify an already created database table. What you are trying to do is typically called "Migration" and there are a couple of different Database Migration tools available for Django.

South

  • Schema Migrations
  • Data Migrations
  • Backwards Migrations

Nash Vegas

  • Schema Migrations
  • Data Migrations

Django Evolution

  • Schema Migrations
  • Data Migrations (Unknown)
  • Backwards Migrations (Unknown)

Of the three South is probably the most widely used but they each have different ways of dealing with migrations. You can see more details on the comparison on Django Packages.


Much of what you're asking about can be done with the django project South. You add it as an INSTALLED_APP. Create a baseline, then as your model changes it creates SQL statements to convert your tables and the rows with-in the tables to the new model format.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜