다음 줄 제거 :이 UploadFile로 모델에서 함수를 트리거
class Invoice(models.Model):
...
invoice_file = models.ManyToManyField(UploadFile, null = True, blank = True)
def save(self, *args, **kwargs):
print('Invoice: saving!')
super(Invoice, self).save(*args, **kwargs)
print 'invoice_file count: %i' % self.invoice_file.count()
if self.invoice_file.count() > 0:
for invoice_file in self.invoice_file.all():
if(invoice_file.locked_status(1)) != 1: raise Exception('Couldn\'t set file locked status to 1 on file %s' % invoice_file.filename)
당신이 데이터베이스 히트를 할 거라면
if self.invoice_file.count() > 0:
을, 당신이 할 수있다뿐만 아니라 송장과 관련된 모든 파일을 검색하여이를 수행하십시오. 이것은 관련된 객체의 '신선한'뷰를 검색하는 추가 이점을 가져야합니다.
문제가 더 심각합니다. ManyToMany 필드는 포함 된 모델이 저장 될 때까지 저장할 수 없습니다. 예 :
class Post(models.Model):
title = models.CharField(max_length=100)
commenters = models.ManyToManyField(User)
me = User.objects.get(username='Josh')
p = Post(title="ManyToManyExample")
p.commenters.add(me) # error, Post does not yet have an ID.
p.save()
p.commenters.add(me) # success!
invoice_file
필드의 이름이 부정확합니다. 컬렉션이기 때문에 invoice_files
이라고해야합니다. Invoice.save
메서드에서 해당 컬렉션에 UploadFile
을 추가하기 전에 관련 컬렉션을 반복하려고합니다. Invoice
모델에 메소드를 추가하는 것이 좋습니다. 송장 대신 .all()
를 사용하는 많은 수의 파일과 관련된
class Invoice(models.Model):
...
def add_invoice_file(self, uploaded_file):
self.invoice_files.add(uploaded_file) # error if the Invoice hasn't been saved yet
for invoice_file in self.invoice_files.all():
status = invoice_file.locked_status(1)
if status != 1:
raise Exception('Blah')
경우 self.invoice_files.filter(locked=False)
을 수행해야합니다. 불필요한 많은 데이터베이스 저장을 피하려면 어쨌든 그렇게하는 것이 좋습니다.
구체적으로 문제를 해결하는 방법을 모르지만 Django 1.2의 m2m 변경된 신호를 사용해보십시오. http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed –
감사합니다. 스파이크! 재미있게 신호를 언급해야한다. 코드를 어지럽히는 것처럼 제거 했으므로 save() 및 delete()를 재정의하는 것이 더 쉽다. 그러나 신호가 더 세밀하게 제어 할 수있는 것 같아요. 그냥 다시 시작하고 다른 결과를 얻을 수 있는지 알아볼 수 있습니다. 제안 해 주셔서 감사합니다! – Harv