-1

I wrote a piece of code that generates graphene input object type dynamically from the database. when I try to run

./manage.py migrate

that code runs before the migration and caused

django.db.utils.ProgrammingError

I have the same issue in run the Pytest too. how can I prevent this code from running before the data migrations

2 Answers2

0

i found this code on the pytest django GitHub issue to unblock database restriction in py test hook.

import pytest
from pytest_django.plugin import _blocking_manager
from django.db.backends.base.base import BaseDatabaseWrapper


@pytest.hookimpl(tryfirst=True)
def pytest_load_initial_conftests(early_config, parser, args):
    _blocking_manager.unblock()
    _blocking_manager._blocking_wrapper = BaseDatabaseWrapper.ensure_connection

and call this hook in pytest.ini with -p argument

0

It doesn't seem like its an issue with pytest, as you are facing this with normal migrations too. Can we see your migration/data migration file? Generally a data migration would come after the table set up.


    import django.db.models.deletion
    from django.db import migrations, models

    def populate_document_owners(apps, schema_editor):
       Document = apps.get_model('some_schema', 'Document')
       User = apps.get_model('some_schema', 'User')
       owner_of_all_docs = User.objects.first()
    
       for d in Document.objects.all():
          d.user = owner_of_all_docs
          d.save()
    
    
    
    class Migration(migrations.Migration):
    
        dependencies = [
            ('some_schema', '0100_previous_migration'),
        ]
    
        operations = [
            migrations.AddField(
                model_name='document',
                name='owner',
                field=models.ForeignKey(
                    on_delete=django.db.models.deletion.CASCADE,
                    related_name='documents',
                    to='some_schema.user',
                ),
            ),
            migrations.RunPython(populate_document_owners),
        ]

rymanso
  • 869
  • 1
  • 9
  • 21