2010-01-15 2 views
1

제가 현재 클래스의 인스턴스가 아닌 일부 개체에서 일부 delete() 및 일부 save() 메서드를 수행하려고합니다. 시도하고 있습니다. 오버로드 된 save() 클래스의 메서드에서이 작업을 수행 할 수 있습니다.다른 클래스의 모델에서 데이터베이스의 개체를 수정할 수 있습니까

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(): 
      #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 

이 작동하지 않습니다와 나는 다음과 같은 예외가 얻을이 수행하려고 할 때 :

Exception AttributeError: "'Cursor' object has no attribute 'connection'" in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x905c3ac>> ignored 
+1

전체 추적을 게시하십시오. 비록 당신이하고있는 일이 가능하지 않더라도, 당신은 그 오류를 얻지 않아야한다. 그래서 이것은 장고 버그 일 수있다. –

답변

0

이 문제가 해결되었습니다. 사실 내가하려는 일을 성취 할 수 있습니다. 문제는 제가 관리자를 완전히 잘못 사용하고 있다는 것이 었습니다. a_tag 위의 코드는 실제로 Category 객체에 대한 참조이므로 delete()을 호출하면 실제로 내 범주가 삭제 되었기 때문에 나는 이상한 예외를 얻고 있습니다. 새로 작동하는 모델 코드의 코드 스 니펫은 다음과 같습니다.

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 
0

을 나는 (당신이 당신의 저장에 ManyToMany를 업데이트하려고 통지 여기에 시나리오에는입니다). this thread에 대한 내 대답을보고 귀하의 상황에 해당되는지 확인하십시오. 관리자 인터페이스를 사용 중이고이 오류가 발생하면 거의 확실하게 문제의 일부입니다. 언급 된 MonkeyPatch를보고 싶을 수도 있습니다.

관련 문제