开发者

Why does model.m2mRelation.remove() not work?

开发者 https://www.devze.com 2023-02-10 08:54 出处:网络
Inother words, why does this work: if choice==Item.DO_ADD_CAT: for item in selected_items: for c in categories:

In other words, why does this work:

if choice==Item.DO_ADD_CAT:
    for item in selected_items:
        for c in categories:
            item.categories.add(Category.objects.get(pk=c))
        item.save()
    messages.success(开发者_高级运维request,'Categories have been added.')

and this not:

if choice==Item.DO_REM_CAT:                        
    for item in selected_items:                            
        for c in categories:                                 
            item.categories.remove(Category.objects.get(pk=c))
        item.save()                            
    messages.success(request,'Categories have been removed.')

Isn't this supposed to be working?

edit: here is the Item model:

class Item(models.Model):
    #public/private state flags
    PRIVATE_STATUS=1
    PUBLIC_STATUS=2
    RELEASED_STATUS=3
    STATUS_CHOICES=((PRIVATE_STATUS ,'private'),
                    (PUBLIC_STATUS  ,'public' ),
                    (RELEASED_STATUS,'released'))
    status = models.IntegerField(choices=STATUS_CHOICES,
                                 default=PRIVATE_STATUS,
                                )
    objects = models.Manager()
    name=models.CharField(max_length=50)
    tags=TagField()
    count=models.IntegerField(blank=True)

    def get_user_path(self,filename):
        return '%s/%s/%s' %( self.creator_id,
                             datetime.date.today(),
                             filename)
    file=models.FileField(upload_to=get_user_path)

    creator = models.ForeignKey(User, related_name='creator')
    categories = models.ManyToManyField(Category,related_name="items",blank=True,null=True)  

and the Category Model:

class Category (models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()
    description = models.TextField(blank=True,help_text='Optional')

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name='Category'
        verbose_name_plural='Categories'


I guess i see the error... As in the django documentation tell us, you can not use remove on an foreignkey with a null=False definition... Related documentation

So prior to the logic of M2M relations, django set your m2m relation as null=False... So possibilities are:

  1. change your m2m definition to null=True
  2. use clear() to remove all elements...


That's exactly how it's supposed to work (especially if the first method works).

Do you get an error message? How do you know it's not working?

Is your code even getting to the remove stage? Use import pdb; pdb.set_trace() and or pepper with print/log statements to make sure the if condition is being met at all and if the object you're trying to remove exists.

I would enter pdb inside your loop and check which categories exist and try removing one of them.

if choice==Item.DO_REM_CAT:                        
    for item in selected_items:                            
        for c in categories:
            import pdb; pdb.set_trace()
            # now check loop.categories.all()
            # item.categories.get(pk=c)
            item.categories.remove(Category.objects.get(pk=c))                              
    messages.success(request,'Categories have been removed.')



log = []
if choice==Item.DO_REM_CAT:                        
    for item in selected_items:                            
        for c in categories:
            category = Category.objects.get(pk=c)
            try:
                item.categories.get(pk=category.pk) # just making sure what we're deleting really exists
                item.categories.remove(category.pk)
                try:
                    item.categories.get(pk=category.pk) # shouldn't be here anymore
                    log.append("Category %s Magically Still Here" %  category)
                except Category.DoesNotExist:
                    log.append("Category %s Successfully Deleted" % category)
            except Category.DoesNotExist:
                log.append("Category %s we attempted to remove from %s doesn't exist" % (category, item))

            return http.HttpResponse('<br><br>'.join(log))
0

精彩评论

暂无评论...
验证码 换一张
取 消