20 Ocak 2009 Salı

Django Admin ManyToMAny Behaviour

In that post want to share an experience with a Django behaviour that took all my day to solve it. In nowadays , i'm working on a freelance project and trying to finish project due to deadline (hate deadlines). Here is the small part of models i'm using

class SchoolSection(models.Model):

class GalleryItem(models.Model):
school_section = models.ManyToManyField(SchoolSection)

A pretty easy structure , the problem occurred when i connected the post_save signal to a method which was using the models above. When a new GalleryItem was saved i wanted to pre-populate some xml files according to new commers. Here is the simple code that was pulling the gallery items :

gi = GalleryItem.objects.filter(school_section = sc[0])

When i save an object i was not able to see the new added in query above. When i saved the object second time (edit->save) the new entry appeared. In a moment when i was going go crazy someone from #django channel told me that Django doesnt save the m2m relationships immediately due to performance issues. Therefore the solution was to override a method in admin part , here is the solution :

class GalleryItemAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(GalleryItemAdmin, self).save_model(request, obj, form, change)

That is all, hope to help someone who has the same problem :)

4 yorum:

ADK dedi ki...

Hey yo man, that's a good solution.
I know u're genius maaan.

Adsız dedi ki...
Bu yorum bir blog yöneticisi tarafından silindi.
sinan dedi ki...

it works like a charm. THANK YOU SO MUCH.

maratych dedi ki...

thanks, worked for me