Class-based views for M2M relationship with intermediate model

前端 未结 5 1787
时光取名叫无心
时光取名叫无心 2020-12-09 13:55

I have a M2M relationship between two Models which uses an intermediate model. For the sake of discussion, let\'s use the example from the manual:

class Pers         


        
5条回答
  •  情书的邮戳
    2020-12-09 14:17

    I was facing pretty the same problem just a few days ago. Django has problems to process intermediary m2m relationships.

    This is the solutions what I have found useful:

    1. Define new CreateView
    class GroupCreateView(CreateView):
        form_class = GroupCreateForm
        model = Group
        template_name = 'forms/group_add.html'
        success_url = '/thanks'
    

    Then alter the save method of defined form - GroupCreateForm. Save is responsible for making changes permanent to DB. I wasn't able to make this work just through ORM, so I've used raw SQL too:

    1. Define new CreateView
    class GroupCreateView(CreateView):
    
    
    class GroupCreateForm(ModelForm):
        def save(self):
            # get data from the form
            data = self.cleaned_data
            cursor = connection.cursor()
            # use raw SQL to insert the object (in your case Group)
            cursor.execute("""INSERT INTO group(group_id, name)
                              VALUES (%s, %s);""" (data['group_id'],data['name'],))
            #commit changes to DB
            transaction.commit_unless_managed()
            # create m2m relationships (using classical object approach)
            new_group = get_object_or_404(Group, klient_id = data['group_id'])
            #for each relationship create new object in m2m entity
            for el in data['members']:
                Membership.objects.create(group = new_group, membership = el)
            # return an object Group, not boolean!
            return new_group
    

    Note:I've changed the model a little bit, as you can see (i have own unique IntegerField for primary key, not using serial. That's how it got into get_object_or_404

提交回复
热议问题