I am trying to make a custom command that I can call up within my Django project but am running into an issue referencing the foreign key it references.
How do I correctly reference the created instance in order to complete the command? Any help would be appreciated.
models.py
class Client(models.Model):
name = models.CharField(max_length=50)
class Project(models.Model):
schema_name = models.CharField(max_length=50)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
command
class Command(BaseCommand):
help = (
"commands, --create_public"
)
def add_arguments(self, parser):
parser.add_argument(
'--create_public',
action='store_true',
help='creates public tenant'
)
def handle(self, *args, **options):
if options['create_public']:
# create your public tenant
client = Client(name='client1')
client.save()
tenant = Project(schema_name='public',
client='client1',
)
tenant.save()
error
ValueError: Cannot assign "client": "Project.client" must be a "Client" instance.
CodePudding user response:
For future reference:
In your class Project
you defined the constraint as being of type Client
so the interpreter expects and instance of that class in the __init__
created by the used framework. Thus raising ValueError
when passing string client1
(although an instance's name).
Solution: pass the instance client
when creating an instance of Project
.