如何删除ManyToMany字段的实例?

时间:2019-03-18 10:06:05

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

我有两个模型:

class Organisation(models.Model):
    user        = models.OneToOneField(settings.AUTH_USER_MODEL,related_name='organisation_user',on_delete=models.CASCADE)
    name        = models.CharField(max_length=100,blank=True)
    location    = models.CharField(max_length=100,blank=True)
    qualification_status = (
        ('Pending for verification','Pending for verification'),
        ('Verified','Verified'),
        )
    qualification   = models.CharField(max_length=100,choices=qualification_status,default='Pending for verification',blank=True)
    members         = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='organisation_members',blank=True)

class Organisation_member(models.Model):
    user            = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
    organisation    = models.ForeignKey(Organisation,on_delete=models.CASCADE,related_name='organisation_staff')
    member_name     = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='organisation_staff_member',on_delete=models.CASCADE,null=True,blank=True)
    is_admin        = models.BooleanField(default=False)

我有创建Organisation_member模型的信号:

@receiver(post_save, sender=Organisation)
def organisation_admin(sender, instance, created, **kwargs):
    for member in instance.members.all():
        if Organisation_member.objects.filter(user=instance.user,organisation=Organisation.objects.filter(user=instance.user,name=instance.name).first(),member_name=member).exists():
            pass
        else:
            Organisation_member.objects.update_or_create(User=instance.User,organisation=Organisation.objects.filter(user=instance.user,name=instance.name).first(),member_name=member,is_admin=False)

该信号表明,当我在manytomany字段中添加成员时,它将自动创建所选成员的Organisation_member对象。

信号工作正常。

我的问题是相反的,即当我尝试删除Organisation_member的对象时,它也应该从父模型的多对多关系中删除该成员。

我已经尝试过了:

@login_required()
def delete_members(request, pk):
    user_organisation = get_object_or_404(Organisation, user=request.user)
    member_to_delete = Organisation_member.objects.filter(pk=pk)
    if member_to_delete.exists():
        member_to_delete[0].delete()
        for member in user_organisation.members.all():
            user_organisation.members.remove(member=member_to_delete[0])
    return redirect(reverse('userprofile:organisation_member_list'))

但是它不会从父模型中删除该成员。

知道解决方案的任何人都可以提供帮助。

谢谢

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

[{'code': '1011', 'balance': -57978.0900005}, {'code': '1101', 'balance': -3550000.0}]

Refer Django offical doc

答案 1 :(得分:0)

使用这种关系的标准方法是在Organisation_member中将through指定为members的{​​{1}}模型。然后,数据库将毫无问题地为您服务。

Organisation

唯一的问题是,您目前在class Organisation(models.Model): members = models.ManyToManyField( settings.AUTH_USER_MODEL, through='Organisation_member') 中有两个对User的引用:Organisation_membermember_name。为什么?您可能只需要一个,而应该删除另一个。如果有理由在user中拥有两个不同的用户,则需要指定用于关系的字段:

Organisation_member

就是这样, members = models.ManyToManyField( settings.AUTH_USER_MODEL, through='Organisation_member', through_fields=('organisation', 'member_name')) 会在您向Organisation_member中添加或删除用户时自动添加和删除。