简体   繁体   中英

Django model foreign key field is not available in migrations during tests

I have this model.

class TransportOrder(SomeMixin, models.Model):
    order = models.ForeignKey(
        to="orders.Order",
        on_delete=models.PROTECT,
        related_name="transport_orders",
        help_text=_("Order which was used for creating"),
        null=True,
        blank=True,
    )
    # Other fields have been removed for simplicity

I have forward function in a migration.

def forward(apps, schema_editor):
    TransportOrder = apps.get_model("transportorders", "TransportOrder")
    
    # There is no `order` field printed result.
    print(dir(TransportOrder))

    # I need to filter something by using `TransportOrder.order` foreign key field here. But I receive the error obviously.

Since there is no order field in TransportOrder model provided by apps.get_model function, I got the following error.

django.core.exceptions.FieldError: Cannot resolve keyword 'order' into field.

However, this only happens while running my tests. Otherwise there is no problem. What can cause this issue?

Tries the django test tool, it is designed to work well with the project, expecially with database and models.

Each time you run tests, Django builds it own test database you can populate from your tests with objects from your project.

https://docs.djangoproject.com/en/3.2/topics/testing/

Apparently somehow, dependencies=[] created by makemigration was not correct in some of the old migrations.

Manually adding some dependencies in some migrations fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM