Home > database >  Django, many to many relationship, how to insert value for all keys in table?
Django, many to many relationship, how to insert value for all keys in table?

Time:02-03

I have 3 models Company, Discount and CompanyDiscountRelation as below:

class Company(models.Model):
    name = models.CharField(max_length=150)

    def __str__(self):
        return self.name


class Discount(models.Model):
    name = models.CharField(max_length=150)
    discount_value = models.IntegerField()

    def __str__(self):
        return self.name


class DiscountCompanyRelation(models.Model):
    company= models.ForeignKey(Company, on_delete=models.CASCADE)
    discount = models.ForeignKey(Discount, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)

I know how to assign a previously created discount to one company. I do it by DiscountCompanyRelationForm and choose company from form list. But i want to assign discount to all companies by one-click. How to do this? I tried get all ID's by: Company.objects.values_list('pk', flat=True) and iterate through them but i don't think that's how it should be done and i have problem to save form by: form.save()

I tried all day but now I gave up. Sorry if this is basic knowledge. I've been working with django for a few days.

CodePudding user response:

If I understand the question, you want to choose a subset of companies in the Company table, and apply a particular Discount.

The first can be a ModelMultipleChoiceField, the second a ModelChoiceField. Put these in a form with appropriate querysets for the companies and discount that can be chosen, and when the form validates, apply the discount:

discount = form.cleaned_data['discount'] 
companies = form.cleaned_data['companies']
for company in companies:
    relation = DiscountCompanyRelation(
        discount = discount,
        company = company,
        is_active = # whatever you need
    )
    relation.save()

You need to think about what happens when a discount is applied to a company which already has a discount. You'll put code in the above loop to check and implement the appropriate action.

I'd strongly recommend specifying a related_name on your ForeignKeys rather than relying on whatever Django generates automagically if you don't.

You might also want to look at the "through" option of a model ManyToManyField, because that's another way to create the same DB structure but brings Django's ManyToMany support code online for you.

  • Related