I have models as follows,
Class Bank(models.Model):
customers = models.ManyToManyField(Customer,'banks', through='bank_customer')
Class Customer(models.Model):
name = models.CharField(max_length=50)
Class Bank_customer(models.Model):
customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
bank = models.ForeignKey(Bank,on_delete=models.CASCADE)
city = models.ForeignKey(City,on_delete=models.CASCADE)
Class City(models.Model):
name = models.CharField(max_length=100)
How do I add Customer objects to Bank? The following does not work
bank.customers.add(customer)
Here bank and customer are saved instances of their classes. Doing this violates not_null constraint for city ForeignKey in Bank_customer table.
First, some general comments. I'm no expert, but I would make this changes to the models to start.
Be carefull with the reserved word
class, it must be all lowercase.When you define the classes, the order is important. The classes that inherit or are backward-related must be defined last. (eg:
Bankmust be defined afterCustomer, if not you'll have an error like "Customer is not defined" or something like that).I think that you may need a
nameattribute/field in theBankmodel. I mean, banks have a name.In the
Bankclass I think it's better to explicitly use the related name keyword:related_name='banks'. It makes readability better.It's more Pythonic to name classes using the CapWords convention (PEP 8). Use
BankCustomerinstead ofBank_customermodel.About your specific question.
I did this:
Then I did
b1.customers.add(c1)and this error was raised:IntegrityError: NOT NULL constraint failed: app2_bankcustomer.city_id. It seems that it was expectingcity_idto havenull=Truein theBankCustomer.I continued with:
And then when I did
b1.customers.add(c1)no errors were raised.The problem is the
IntegrityErrorerror, apparently:So you can make a little change to the
BankCustomer. You addnull=Truein thecityfield.(Don't forget to run makemigrations and migrate)
After this, no errors are raised.
Some other sources that discuss the issue:
django.db.utils.IntegrityError: NOT NULL constraint failed: app.area_id
django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image ERROR WITH IMAGE FIELD
https://code.djangoproject.com/ticket/21783
https://forum.djangoproject.com/t/polls-not-null-constraint-failed/4396/2
https://github.com/sibtc/django-beginners-guide/issues/20
If you check the admin you'll see that the
Bankmodel only acceptsnameand nocustomers.Which I think is logical because you want to use the
BankCustomer(in your code:Bank_customer).I hope this helps.