mardi 16 avril 2019

Model creation order when testing in django?

I’ve got these two models (examples) and when I’m trying to run my tests - it errors out saying: no such table: my_app_modelA - if I scroll up I can see that it is bombing out when creating modelB (which I assume is due to the default being applied). Is there a way to order these so that modelA will always get created before modelB? Or should I not be referencing that method as a default attribute? Just trying to get my tests working and this is my sticking point.

My models look like this:

class modelA(models.Model):
    attribute = models.IntegerField()
    active = models.BooleanField(default=False)

    @classmethod
    def get_active_attribute(cls):
        return modelA.objects.get(active=True).attribute

class modelB(models.Model):
    attribute = models.IntegerField(default=modelA.get_active_attribute())

My questions are:

  • Is that an acceptable thing to do - having default call another model method?

  • Is there a way to handle the creation of those models in a way that I can guarantee that modelA gets created first so modelB can succesfully create in my tests?

Aucun commentaire:

Enregistrer un commentaire