Working on a Django app with two models (A and B), B has a field link
which is a foreign key relationship to A:
# models.py
class A(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=15)
my_bool = models.BooleanField(default=True)
class B(models.Model):
link = models.ForeignKey(A)
b_bool = models.BooleanField(default=link.my_bool) # Error!
I would like for the b_bool
field to have the linked my_bool
value as a default if no B.b_bool
is provided via graphene mutation.
Currently, using link.my_bool
as a default raises the following error when making migrations:
AttributeError: 'ForeignKey' object has no attribute 'my_bool'
I don't think it will work like that. Instead, try overriding save()
method:
class B(models.Model):
link = models.ForeignKey(A)
b_bool = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if not self.b_bool:
self.b_bool = self.link.my_bool
super(B, self).save(*args, **kwargs)