Как перенести модель из одного приложения django в новое?

Вот JavaScript 1.6, совместимый реализация Array.indexOf:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
}

125
задан Welbog 11 August 2009 в 11:45
поделиться

2 ответа

Как перейти с использованием юга.

Допустим, у нас есть два приложения: общее и конкретное:

myproject/
|-- common
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   `-- 0002_create_cat.py
|   `-- models.py
`-- specific
    |-- migrations
    |   |-- 0001_initial.py
    |   `-- 0002_create_dog.py
    `-- models.py

Теперь мы хотим переместить модель common.models.cat в определенное приложение (а именно в specific.models.cat). Сначала внесите изменения в исходный код, а затем запустите:

$ python manage.py schemamigration specific create_cat --auto
 + Added model 'specific.cat'
$ python manage.py schemamigration common drop_cat --auto
 - Deleted model 'common.cat'

myproject/
|-- common
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   |-- 0002_create_cat.py
|   |   `-- 0003_drop_cat.py
|   `-- models.py
`-- specific
    |-- migrations
    |   |-- 0001_initial.py
    |   |-- 0002_create_dog.py
    |   `-- 0003_create_cat.py
    `-- models.py

Теперь нам нужно отредактировать оба файла миграции:

#0003_create_cat: replace existing forward and backward code
#to use just one sentence:

def forwards(self, orm):
    db.rename_table('common_cat', 'specific_cat') 

    if not db.dry_run:
        # For permissions to work properly after migrating
        orm['contenttypes.contenttype'].objects.filter(
            app_label='common',
            model='cat',
        ).update(app_label='specific')

def backwards(self, orm):
    db.rename_table('specific_cat', 'common_cat')

    if not db.dry_run:
        # For permissions to work properly after migrating
        orm['contenttypes.contenttype'].objects.filter(
            app_label='specific',
            model='cat',
        ).update(app_label='common')

#0003_drop_cat:replace existing forward and backward code
#to use just one sentence; add dependency:

depends_on = (
    ('specific', '0003_create_cat'),
)
def forwards(self, orm):
    pass
def backwards(self, orm):
    pass

Теперь оба миграционных приложения знают об изменениях, и жизнь отстойная :-) Установление этой взаимосвязи между миграциями - ключ к успеху. Теперь, если вы это сделаете:

python manage.py migrate common
 > specific: 0003_create_cat
 > common: 0003_drop_cat

выполнит и миграцию, и

python manage.py migrate specific 0002_create_dog
 < common: 0003_drop_cat
 < specific: 0003_create_cat

перенесет все вниз.

Обратите внимание, что для обновления схемы я использовал обычное приложение, а для перехода на более раннюю версию я использовал конкретное приложение. Это потому, что здесь работает зависимость.

183
ответ дан 24 November 2019 в 01:00
поделиться

Models aren't very tightly coupled to apps, so moving is fairly simple. Django uses the app name in the name of the database table, so if you want to move your app you can either rename the database table via an SQL ALTER TABLE statement, or - even simpler - just use the db_table parameter in your model's Meta class to refer to the old name.

If you've used ContentTypes or generic relations anywhere in your code so far, you will probably want to rename the app_label of the contenttype pointing at the model that's moving, so that existing relations are preserved.

Of course, if you don't have any data at all to preserve, the easiest thing to do is to drop the database tables completely and run ./manage.py syncdb again.

7
ответ дан 24 November 2019 в 01:00
поделиться
Другие вопросы по тегам:

Похожие вопросы: