Django: ManyToMany filter matching on ALL items in a list

Similar to @goliney’s approach, I found a solution. However, I think the efficiency could be improved. # A sample set of authors target_authors = set((author_1, author_2)) # To reduce the search space, first retrieve those books with just 2 authors. candidate_books = Book.objects.annotate(c=Count(‘authors’)).filter(c=len(target_authors)) # In each iteration, we filter out those books which don’t contain … Read more

Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead

You need to get the User object and then add it to emails_for_help field. You can’t add an object to ManyToManyField when creating an instance. Have a look at the doc. class Set_user(FormView): template_name=”pkm_templates/set_up_user.html” form_class = Set_User_Form success_url=”/thanks/” def form_valid(self, form): org = form.cleaned_data.get(‘organization’) emails = form.cleaned_data.get(“share_email_with”) users = User.objects.filter(email__in=emails) instance = Setupuser.objects.create(organization=org) for user … Read more

Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields

I stumbled upon this and although I didn’t care about my data much, I still didn’t want to delete the whole DB. So I opened the migration file and changed the AlterField() command to a RemoveField() and an AddField() command that worked well. I lost my data on the specific field, but nothing else. I.e. … Read more