Can you/should you modify objects in the database in the model of other classes
I want to perform some delete()
and some save()
methods on some objects that are not an instance of the current class I'm in. I'm trying to do this in an overloaded save()
method of a class. Here is the scenerio:
class Item(models.Model):
name = models.CharField(max_length=500)
category = models.ForeignKey(Category, null=True, related_name='add_item')
tag = models.ManyToManyField(Category, null=True, related_name='tag_item')
def save(self, *args, **kwargs):
super(Item, self).save(*args, **kwargs)
for a_tag in self.tag.all():
开发者_JS百科 #do stuff here
a_tag.delete()
cat = self.category
while cat is not None:
cat.add_item.add(self)
#do stuff here
cat.save()
cat = cat.parent
This doesn't work and when I try to do this I get the following exception:
Exception AttributeError: "'Cursor' object has no attribute 'connection'" in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x905c3ac>> ignored
I notice you are trying to update a ManyToMany in your save(). You might take a look at my answer to this thread and see if it applies to your situation. If you are using the admin interface and are encountering this error, then it is almost certainly part of the problem you are having. You also might want to look at the MonkeyPatch mentioned.
I ended up resolving this issue. You can in fact accomplish what I was trying to do. The issue was that I was using the managers completely wrong. a_tag
above was actually a reference to a Category object, so calling delete()
on that was actually deleting my Categories, which is why I was getting the weird Exception I'm assuming. Here's a code snippet of the newly working model code:
def save(self, *args, **kwargs):
super(Item, self).save(*args, **kwargs)
for a_tag in self.tag.all():
a_tag.tag_item.clear()
cat = self.category
while cat is not None:
cat.tag_item.add(self)
cat = cat.parent
精彩评论