django manytomany model relationship crashing admin on object create









up vote
1
down vote

favorite












I have an Event object in my postgres db, and created a new Collection object to group events by theme via a ManyToMany field relationship:



class Collection(models.Model):
event = models.ManyToManyField('Event', related_name='collections')
name = models.CharField(blank=True, max_length=280)
slug = AutoSlugField(populate_from='name')
image = models.ImageField(upload_to='collection_images/', blank=True)
description = models.TextField(blank=True, max_length=1000)
theme = models.ManyToManyField('common.Tag', related_name='themes')
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
is_active = models.BooleanField(default=False)

def __str__(self):
return self.name

def get_absolute_url(self):
return reverse('collection', args=[self.slug])

def clean(self):
# because of the way db saves M2M relations, collection doesn't have a
# type at this time yet, so image inheritance is
# called from the signal which is triggered when M2M is created
# (that means if an image is later deleted, it won't inherit a new
# one when collection is saved)
if self.image:
validate_hero_image(self.image, 'image')

def save(self, *args, **kwargs):
try:
self.full_clean()
except ValidationError as e:
log.error('Collection validation error (name = %s): %s' % (self.name, e))
return super(Collection, self).save(*args, **kwargs)


in my admin, I'm defining and registering CollectionAdmin like this:



class CollectionAdmin(admin.ModelAdmin):
model = Collection
verbose_name = 'Collection'
list_display = ( 'name', )


however, if I go into admin and attempt to create a Collection "GET /admin/app/collection/add/" 200, the request frequently times out and the query load on my database from the Event M2M relationship seems quite heavy from logging. For reference currently the db has ~100,000 events. are there better ways to (re)structure my admin fields so I can select specific events (by name or id) to add to a Collection without effectively requesting a QuerySet of all events when that view is loaded (or creating them in db via shell)? thanks










share|improve this question

























    up vote
    1
    down vote

    favorite












    I have an Event object in my postgres db, and created a new Collection object to group events by theme via a ManyToMany field relationship:



    class Collection(models.Model):
    event = models.ManyToManyField('Event', related_name='collections')
    name = models.CharField(blank=True, max_length=280)
    slug = AutoSlugField(populate_from='name')
    image = models.ImageField(upload_to='collection_images/', blank=True)
    description = models.TextField(blank=True, max_length=1000)
    theme = models.ManyToManyField('common.Tag', related_name='themes')
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=False)

    def __str__(self):
    return self.name

    def get_absolute_url(self):
    return reverse('collection', args=[self.slug])

    def clean(self):
    # because of the way db saves M2M relations, collection doesn't have a
    # type at this time yet, so image inheritance is
    # called from the signal which is triggered when M2M is created
    # (that means if an image is later deleted, it won't inherit a new
    # one when collection is saved)
    if self.image:
    validate_hero_image(self.image, 'image')

    def save(self, *args, **kwargs):
    try:
    self.full_clean()
    except ValidationError as e:
    log.error('Collection validation error (name = %s): %s' % (self.name, e))
    return super(Collection, self).save(*args, **kwargs)


    in my admin, I'm defining and registering CollectionAdmin like this:



    class CollectionAdmin(admin.ModelAdmin):
    model = Collection
    verbose_name = 'Collection'
    list_display = ( 'name', )


    however, if I go into admin and attempt to create a Collection "GET /admin/app/collection/add/" 200, the request frequently times out and the query load on my database from the Event M2M relationship seems quite heavy from logging. For reference currently the db has ~100,000 events. are there better ways to (re)structure my admin fields so I can select specific events (by name or id) to add to a Collection without effectively requesting a QuerySet of all events when that view is loaded (or creating them in db via shell)? thanks










    share|improve this question























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I have an Event object in my postgres db, and created a new Collection object to group events by theme via a ManyToMany field relationship:



      class Collection(models.Model):
      event = models.ManyToManyField('Event', related_name='collections')
      name = models.CharField(blank=True, max_length=280)
      slug = AutoSlugField(populate_from='name')
      image = models.ImageField(upload_to='collection_images/', blank=True)
      description = models.TextField(blank=True, max_length=1000)
      theme = models.ManyToManyField('common.Tag', related_name='themes')
      date_created = models.DateTimeField(auto_now_add=True)
      date_updated = models.DateTimeField(auto_now=True)
      is_active = models.BooleanField(default=False)

      def __str__(self):
      return self.name

      def get_absolute_url(self):
      return reverse('collection', args=[self.slug])

      def clean(self):
      # because of the way db saves M2M relations, collection doesn't have a
      # type at this time yet, so image inheritance is
      # called from the signal which is triggered when M2M is created
      # (that means if an image is later deleted, it won't inherit a new
      # one when collection is saved)
      if self.image:
      validate_hero_image(self.image, 'image')

      def save(self, *args, **kwargs):
      try:
      self.full_clean()
      except ValidationError as e:
      log.error('Collection validation error (name = %s): %s' % (self.name, e))
      return super(Collection, self).save(*args, **kwargs)


      in my admin, I'm defining and registering CollectionAdmin like this:



      class CollectionAdmin(admin.ModelAdmin):
      model = Collection
      verbose_name = 'Collection'
      list_display = ( 'name', )


      however, if I go into admin and attempt to create a Collection "GET /admin/app/collection/add/" 200, the request frequently times out and the query load on my database from the Event M2M relationship seems quite heavy from logging. For reference currently the db has ~100,000 events. are there better ways to (re)structure my admin fields so I can select specific events (by name or id) to add to a Collection without effectively requesting a QuerySet of all events when that view is loaded (or creating them in db via shell)? thanks










      share|improve this question













      I have an Event object in my postgres db, and created a new Collection object to group events by theme via a ManyToMany field relationship:



      class Collection(models.Model):
      event = models.ManyToManyField('Event', related_name='collections')
      name = models.CharField(blank=True, max_length=280)
      slug = AutoSlugField(populate_from='name')
      image = models.ImageField(upload_to='collection_images/', blank=True)
      description = models.TextField(blank=True, max_length=1000)
      theme = models.ManyToManyField('common.Tag', related_name='themes')
      date_created = models.DateTimeField(auto_now_add=True)
      date_updated = models.DateTimeField(auto_now=True)
      is_active = models.BooleanField(default=False)

      def __str__(self):
      return self.name

      def get_absolute_url(self):
      return reverse('collection', args=[self.slug])

      def clean(self):
      # because of the way db saves M2M relations, collection doesn't have a
      # type at this time yet, so image inheritance is
      # called from the signal which is triggered when M2M is created
      # (that means if an image is later deleted, it won't inherit a new
      # one when collection is saved)
      if self.image:
      validate_hero_image(self.image, 'image')

      def save(self, *args, **kwargs):
      try:
      self.full_clean()
      except ValidationError as e:
      log.error('Collection validation error (name = %s): %s' % (self.name, e))
      return super(Collection, self).save(*args, **kwargs)


      in my admin, I'm defining and registering CollectionAdmin like this:



      class CollectionAdmin(admin.ModelAdmin):
      model = Collection
      verbose_name = 'Collection'
      list_display = ( 'name', )


      however, if I go into admin and attempt to create a Collection "GET /admin/app/collection/add/" 200, the request frequently times out and the query load on my database from the Event M2M relationship seems quite heavy from logging. For reference currently the db has ~100,000 events. are there better ways to (re)structure my admin fields so I can select specific events (by name or id) to add to a Collection without effectively requesting a QuerySet of all events when that view is loaded (or creating them in db via shell)? thanks







      django postgresql django-models django-admin






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 21:35









      Chris B.

      44831432




      44831432






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          There are multiple ways to accomplish this. For example, you could override the form fields the admin uses and specify another widget to use, like NumberInput.



          You could also add your event model field to the raw_id_fields attribute of ModelAdmin. By doing so, Django won't try to create a fully populated select input but will offer you a way to search for events manually if needed:



          class CollectionAdmin(admin.ModelAdmin):
          model = Collection
          verbose_name = 'Collection'
          list_display = ('name', )
          raw_id_fields = ('event', )





          share|improve this answer




















          • thanks Soren. raw_id_fields is a great field alternative for this use case
            – Chris B.
            Nov 11 at 23:33










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253469%2fdjango-manytomany-model-relationship-crashing-admin-on-object-create%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          There are multiple ways to accomplish this. For example, you could override the form fields the admin uses and specify another widget to use, like NumberInput.



          You could also add your event model field to the raw_id_fields attribute of ModelAdmin. By doing so, Django won't try to create a fully populated select input but will offer you a way to search for events manually if needed:



          class CollectionAdmin(admin.ModelAdmin):
          model = Collection
          verbose_name = 'Collection'
          list_display = ('name', )
          raw_id_fields = ('event', )





          share|improve this answer




















          • thanks Soren. raw_id_fields is a great field alternative for this use case
            – Chris B.
            Nov 11 at 23:33














          up vote
          1
          down vote



          accepted










          There are multiple ways to accomplish this. For example, you could override the form fields the admin uses and specify another widget to use, like NumberInput.



          You could also add your event model field to the raw_id_fields attribute of ModelAdmin. By doing so, Django won't try to create a fully populated select input but will offer you a way to search for events manually if needed:



          class CollectionAdmin(admin.ModelAdmin):
          model = Collection
          verbose_name = 'Collection'
          list_display = ('name', )
          raw_id_fields = ('event', )





          share|improve this answer




















          • thanks Soren. raw_id_fields is a great field alternative for this use case
            – Chris B.
            Nov 11 at 23:33












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          There are multiple ways to accomplish this. For example, you could override the form fields the admin uses and specify another widget to use, like NumberInput.



          You could also add your event model field to the raw_id_fields attribute of ModelAdmin. By doing so, Django won't try to create a fully populated select input but will offer you a way to search for events manually if needed:



          class CollectionAdmin(admin.ModelAdmin):
          model = Collection
          verbose_name = 'Collection'
          list_display = ('name', )
          raw_id_fields = ('event', )





          share|improve this answer












          There are multiple ways to accomplish this. For example, you could override the form fields the admin uses and specify another widget to use, like NumberInput.



          You could also add your event model field to the raw_id_fields attribute of ModelAdmin. By doing so, Django won't try to create a fully populated select input but will offer you a way to search for events manually if needed:



          class CollectionAdmin(admin.ModelAdmin):
          model = Collection
          verbose_name = 'Collection'
          list_display = ('name', )
          raw_id_fields = ('event', )






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 22:05









          Sören Weber

          1918




          1918











          • thanks Soren. raw_id_fields is a great field alternative for this use case
            – Chris B.
            Nov 11 at 23:33
















          • thanks Soren. raw_id_fields is a great field alternative for this use case
            – Chris B.
            Nov 11 at 23:33















          thanks Soren. raw_id_fields is a great field alternative for this use case
          – Chris B.
          Nov 11 at 23:33




          thanks Soren. raw_id_fields is a great field alternative for this use case
          – Chris B.
          Nov 11 at 23:33

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53253469%2fdjango-manytomany-model-relationship-crashing-admin-on-object-create%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

          Museum of Modern and Contemporary Art of Trento and Rovereto