[Python] How to use add(), set() and clear() methods of ManyRelatedManager in Django...

Discussão em 'Python' iniciado por Stack, Outubro 6, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página