[Answer]-How to save a many to many model in django

1👍

rules is not really a field on the model, it’s an entry in a linking table – so it can’t be saved until the Module entry exists. Also note that your loop is such that it will never consist of more than one Rules object, because you overwrite the rules variable each time. Instead you should simply get all the Rules and add them in one go.

module = models.Module(name=module_name,
                       description=module_description)
module.save()
rules = models.Rule.objects.filter(pk__in=rule_ids)
module.rules = rules

There’s no need to save again after that: assigning to a related queryset does the database operation automatically. Also note that filter will not raise a DoesNotExist exception: if there is no matching rule, then there simply won’t be an element in the resulting queryset.

0👍

you are overriding the rules queryset inside try and filter() doesnot raise DoesNotExist exception btw..

try this:

module = models.Module(name=module_name,description=module_description)
module.save()
#first save 'module' and add 'rules' from filter()-result

rules = models.Rule.objects.filter(pk__in=rule_ids)
module.rules = rules 
module.save()

more about how to save m2m in django

Leave a comment