【问题标题】:Django - YAML App Fixtures Order ConflictingDjango - YAML 应用程序夹具顺序冲突
【发布时间】:2012-02-28 12:34:34
【问题描述】:

我有从一个模型(UserProfile 模型)中的模型到我创建的另一个应用程序的带有外键的单独应用程序。当我尝试syncdb 时,我发现外键 id 为 NULL,即使我在该应用程序中有一个固定装置。有没有办法指定 YAML 文件的加载顺序?

这是应用程序结构的样子 -

个人资料/

# models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    school = models.ForeignKey(School)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

# fixtures/initial_data.yaml
-   fields:
        username: admin
        password: ***password hash here***
        date_joined: 2012-02-01 01:00:00
        email: email@email.com
        last_name: Last
        first_name: First
        groups: []
        is_active: true
        is_staff: true
        is_superuser: true
        last_login: 2012-02-01 01:01:00
        user_permissions: []
    model: auth.user
    pk: 1
-   fields:
        user: 1
        school: 1
    model: profile.UserProfile
    pk: 1

学校/

# models.py
class School(models.Model):
    name = models.CharField(max_length=100)

# fixtures/initial_data.yaml
-   fields:
        name: "School"
    model: school.School
    pk: 1

syncdb 我得到:

IntegrityError: profile_userprofile.school_id may not be NULL

这一定意味着它在学校之前保存了 UserProfile 模型。所以,我想知道是否有可能重新排序 yaml 文件或以某种方式将学校归因于我的 UserProfile 而不允许学校为 NULL。

在 settings.py 中,我在已安装的应用中加载 school,然后是 profile

【问题讨论】:

    标签: django foreign-keys yaml django-syncdb


    【解决方案1】:

    这里正确的做法是使用natural keys

    如果你不能使用,你可以手动加载fixture,只需重命名它们并按你需要的顺序通过manage.py loaddata加载。

    【讨论】:

    • 感谢您指出资源。设置 natural_key.dependencies 似乎是序列化的解决方案,但是它不会在同步数据库期间设置依赖项。不过感谢您提供的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2016-01-23
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多