Django, South and the --freeze command
I'm trying to get started with South data migrations. I found this SO question: South data migration 'instance' error when using south freeze orm, and tried the commands listed there but it does not seem to help.
I have 2 apps A and B in my project, here are their models:
# /app_A/models.py
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length = 100)
department = models.ForeignKey("Department")
开发者_如何学JAVAmanager = models.ForeignKey("self", blank = True, null = True)
birthdate = models.DateField()
# /app_B/models.py
from django.db import models
from hr_manager.models import Employee
class Task(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
assigned_to = models.ForeignKey(Employee, null=False, blank=False)
seniority = models.IntegerField(default=0)
age = models.IntegerField(default=0)
I am trying to generate a data migration for app_B so that it calculates the age and senority of the Employee the Task is assigned to and store it in the Task itself. I ran :
./manage.py datamigration app_B populate_age_and_senority --freeze app_A
the --freeze option should make the models of app_A available in the migration through orm['app_1.']. I then edited the migration created this way:
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
import datetime
def calculate_age(born):
''' Returns the age from a starting date '''
...
birthdate = orm['hr_manager.Employee'].birthdate
date_joined = orm['hr_manager.EmployeeHistory'].date_joined
orm.Task.age = calculate_age(birthdate)
orm.Task.seniority = calculate_age(date_joined)
orm.Task.save()
def backwards(self, orm):
raise RuntimeError("Cannot reverse this migration.")
And then ran:
./manage.py migrate app_B
Here is what I obtained:
AttributeError: type object 'Employee' has no attribute 'birthdate'
Did I do something wrong?
Thanks in advance for your help!
The line:
orm['hr_manager.Employee']
Accesses the Model
, not an instance. You need to access an instance via the usual:
orm['hr_manager.Employee'].objects.all()
orm['hr_manager.Employee'].objects.get(...)
...
methods.
精彩评论