django model on_delete pass self to models.SET()

后端 未结 1 559
[愿得一人]
[愿得一人] 2021-01-21 08:48

For example, I have a Book model, each book has its author and tag.

def get_authors_first_tag(book):
    try:
        tag = book.author.tags.first()
    except:         


        
1条回答
  •  伪装坚强ぢ
    2021-01-21 09:14

    The SET() doesn't accept any arguments, so you should use the signal receiver:

    from django.db.models.signals.pre_delete
    from django.dispatch import receiver
    
    @receiver(pre_delete, sender=Tag)
    def reset_tag(sender, **kwargs):
        tag = kwargs['instance']
        for book in books.filter(tag=tag):
            book.tag = book.author.tags.first()
            book.save()
    

    Put this code into your models.py or make sure the file you put the receiver into is imported at the startup, so that the receiver is actually connected.

    0 讨论(0)
提交回复
热议问题