我和我的一个模特有一个ManyToMany关系。在删除子项时,我想删除该关系,但保留其他对象可能正在使用的记录。在调用删除视图时,我收到一个AttributeError错误:
异常值:'QuerySet'对象具有 没有属性'clear'
这是我的models.py:
class Feed(models.Model):
username = models.CharField(max_length=255, unique=True)
class Digest(models.Model):
name = models.CharField(max_length=255)
user = models.ForeignKey(User)
items = models.PositiveIntegerField()
keywords = models.CharField(max_length=255, null=True, blank=True)
digest_id = models.CharField(max_length=20, unique=True)
time_added = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=1)
feeds = models.ManyToManyField(Feed)
views.py的相关部分:
def feed_delete(request, id):
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
Feed.objects.get(id=request.POST.get('id')).digest_set.filter(id=id).clear()
return HttpResponseRedirect(digest.get_absolute_url())
答案 0 :(得分:6)
清除摘要实例上的字段
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
digest.feeds.clear()
#do your processing
回应你的评论。
digest = get_object_or_404(Digest, id=id)
if digest.user == request.user:
feed=digest.feeds.get(id=2)#get an instance of the feed to remove
digest.feeds.remove(feed)#remove the instance
希望这有帮助!