youssefmohamed
youssefmohamed

Reputation: 145

Linking two models automatically in django

I would like when i create new order to be linked to this company. now, i have to choose it manually

class Company(models.Model):
    name = models.CharField(max_length=64)
    address = models.TextField(max_length=250)

class Order(models.Model):
    company = models.ForeignKey('Company', on_delete=models.CASCADE)
    order_date = models.CharField(max_length=64)
    order_notes = models.TextField(max_length=250)

Upvotes: 1

Views: 79

Answers (1)

quqa123
quqa123

Reputation: 675

First of all if every Order is connected to this particular Company creating Foreign Key is overintended. If you still want to do this for some reason here is the solution.

class Order(models.Model):
    company = models.ForeignKey('Company', on_delete=models.CASCADE)
    order_date = models.CharField(max_length=64)
    order_notes = models.TextField(max_length=250)

    def save(self, *args, **kwargs):
        # u have to have a new order in db
        super().save(*args, **kwargs)
        # then assing this particular company
        self.company = Company.objects.get(name='the_company_name', address='the_company_address')
        # and again save the changes
        super().save(*args, **kwargs)

but if you want to do this this way consider making the Company name and address unique_together

Upvotes: 1

Related Questions