在Django的ManytoMany字段中删除一个特定的关系

时间:2019-04-01 04:10:14

标签: django-models django-views many-to-many

我是编码的新手,我点击了http://charlesleifer.com/blog/self-referencing-many-many-through/链接,尝试创建一个简单的朋友列表。我在创建允许用户从html添加或删除联系人的视图时遇到了麻烦。我认为,如果我可以删除此ManytoMany关系的ID,则可以删除此m2m字段中的项目,但无法弄清楚如何加载正确的ID

我尝试使用.clear()和.delete(),但是它们会删除用户的所有关系,我要做的就是删除两个用户之间的特定关系。

这是我自定义的用户模型和联系人:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255,unique=True)
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=25)
    contacts = models.ManyToManyField('self', through='Contact', symmetrical=False, related_name='related_to+')
    
    objects = UserManager()

    USERNAME_FIELD = 'email'
    
    
    def __str__(self):
        return self.email

    def add_contact(self, person, symm=True):
        contact, created = Contact.objects.get_or_create(
            from_person=self,
            to_person=person,
        )
        if symm:
            person.add_contact(self, False)
        return contact
    
    def remove_contact(self, person, symm=True):
        Contact.objects.filter(
            from_person=self,
            to_person=person,).delete()
        if symm:
            person.remove_contact(self, False)

class Contact(models.Model):
    current_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE)
    contact_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='contact_name', null = True)

这是我用来显示用户具有的每个联系人的HTML前端表

        <table id="datatables-basic" class="table table-lined" style="width:100%">
          <span class="align-right" style="float:right">
              <a href="#"><img src="{% static 'images/_ionicons_svg_md-add-circle-outline.svg' %}" alt="" style="width:3em;height: 3em;" data-toggle="modal" data-target="#addcontactModalCenter"></a>
            </span>
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
          {% if user.contacts %}
            {% for contact in user.contacts.all %}
            <tr>
              <td>{{ contact.first_name }} {{ contact.last_name }}</td>
              <td>{{ contact.title}}</td>
              <td>{{ contact.email }}</td>
              <td>
                <a href="#"><img src="{% static 'images/_ionicons_svg_md-trash.svg' %}" alt="" style="width:1.5em;height: 1.5em;" data-toggle="modal" data-target="#removecontactModalCenter"></a>
              </td>
            </tr>
            {% endfor %}
          {% endif %}
          </tbody>
        </table>

当用户单击垃圾桶图标以删除联系人时,我使用模式请求用户确认,然后再删除此联系人。确认后,将该用户从用户的联系人列表中删除。

<div class="modal fade" id="removecontactModalCenter" tabindex="-1" role="dialog" aria-labelledby="removecontactModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-body">
            <form action="{% url 'accounts:remove_contact' %}" method="POST">
            {% csrf_token %}
            <div class="modal-body">
                <h5><strong>Remove from your contact?</strong></h5>
                <input type="hidden" name="contact_id" value="{{ Contact.id }}">
              </div>
                <div class="modal-footer">           
                  <input type="submit" class="btn btn-primary" value="Yes, Remove">
                  <input type="submit" class="btn btn-secondary" data-dismiss="modal" value= "Close">
                </div>
            </form>
        </div>
      </div>
    </div>
  </div>

但是,我被困在视图部分,无法弄清楚如何在表中调用正确的对应联系人ID,并将其从用户的联系人列表中删除:

def remove_contact(request):
   if request.method == 'POST':
       contact = Contact.objects.get(Contact.id)
       contact.delete()
       return redirect('accounts:contacts')

请帮助谢谢!

0 个答案:

没有答案