简体   繁体   English

Django:删除对象中的m2m关系

[英]Django: removing m2m relation in object

I just started playing with Django, I love it! 我刚开始玩Django,我喜欢它! I am still working my way around with the Django ORM though... 我仍然在使用Django ORM,但是......

At the moment I have a model Shift with a m2m relationship with users: 目前我有一个与用户建立m2m关系的模型Shift:

class Shift(models.Model):
    users = models.ManyToManyField(User) 

I want to define a view that checks if a M2M relationship exists, if it does, it removes this relationship. 我想定义一个检查M2M关系是否存在的视图,如果存在,则删除此关系。 This is where I am stuck: I am able to lookup if a relationship exists, but I am not able to remove it. 这就是我被困住的地方:我能够查找是否存在关系,但我无法将其删除。 What is wrong with my code? 我的代码出了什么问题?

def remove_if_exists(request, shift_id, username):
    shift = get_object_or_404(Shift, pk=shift_id)
    if shift.users.filter(username=username).exists()
        shift.users.remove(username)

The trouble with your code is that the relationship is not with a username, but with a User object. 代码的问题在于关系不是用户名,而是用户对象。 So your call to remove should have a User object as its argument. 因此,对remove的调用应该有一个User对象作为参数。 You need to actually get the relevant user from the db first, then call remove with that object. 您需要先从db中获取相关用户,然后使用该对象调用remove。

However, there is a shortcut: remove does not raise an error if the object is not in the related set, so you can skip the exists call. 但是,有一个快捷方式:如果对象不在相关集中,则remove不会引发错误,因此您可以跳过exists调用。 That gives just: 这只是:

user = User.objects.get(username=username)
shift = get_object_or_404(Shift, pk=shift_id)
shift.users.remove(user)

我自己的一些愚蠢的语法错误应该是:

 shift.users.remove(User.objects.get(username=username))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM