Django Many-to-Many relation insertion control

后端 未结 2 678
再見小時候
再見小時候 2021-01-12 15:40

I have the following models:

class Item(models.Model):
    # fields
    # ...

class Collection(models.Model):
    ite         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 16:40

    1. The pre_save signal is called before saving an instance. But you are not able to abort the save operation from there. A better solution would be to add a new method to your Collection model, which is responsible for checking if an Item can be added:

      class Collection(models.Model):
          items = models.ManyToManyField(Item, related_name="collections")
      
          ...
      
          def add_item(self, item):
              if check_if_item_can_be_added(item):
                  items.add(item)
                  self.save()
      
      def check_if_item_can_be_added(self, item):
          # do your checks here
      
    2. When adding an instance to a m2m field, the save method does not get called. You are right, the m2m_changed signal is the way to go. You can safely update the collection instance in there.

提交回复
热议问题