Im trying to create a tuple from another model's objects and use it in another model. it works just fine but when when I want to start my app and makemigrations, it gives me the error that the model you are trying to use is not created yet, obviously! therefore, I need an if statement to check if that model table is not created dont do anything. this is my Model:
class Field(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=16, default='default')
title = CharField(max_length=32)
and my tuple:
INTERESTS = (Field.objects.values_list('slug', 'title'))
and this is the error I get:
django.db.utils.OperationalError: no such table: reg_field
how can I bypass this error? I need something like this: if Field exists then: INTERESTS = the above, else INTERESTS = ()
CodePudding user response:
Have you tried commenting this line:
# INTERESTS = (Field.objects.values_list('slug', 'title'))
Then running makemigrations
and migrate
and then trying again?
If you're trying to execute code that makes use of an unmigrated model it certainly won't work.
--- OR --
Move that row inside a method so it's not evaluated when executing makemigrations
def my_method():
INTERESTS = (Field.objects.values_list('slug', 'title'))
CodePudding user response:
What you are trying to do is wrong. It is wrong to try to create tables while running your code.
Instead, make sure your tables are set but empty.
You can check if the table is empty instead.
To check if a table is empty.. Use this
Objs = Mymodel.objects.all()
If objs is None:
# your code goes here