python - Django deleting a model instance with no more related ForeignKey items in another model? -


in model below, when artist deleted through admin, it'll confirm , delete related songs. however, when delete song through admin, i'd delete artist if artist has no more related items in song. there model option in admin?

how should done in custom view not inside of modeladmin?

class artist (models.model):     name = models.charfield(max_length=100)      def __str__(self):         return self.name  class genre (models.model):     name = models.charfield(max_length=100)     def __str__(self):         return self.name  class song (models.model):         artist = models.foreignkey(artist, on_delete=models.cascade)     genre = models.foreignkey(genre, null=true, blank=true, on_delete=models.set_null)     title = models.charfield(max_length=100)     mix = models.charfield(max_length=100, blank=true)      def __str__(self):         return self.title 

could through delete method of song.

def delete(*args, **kwargs): artist = self.artist super(song, self).delete(*args, **kwargs) if artist.song_set.count() == 0: artist.delete()

or similar.


Comments

Popular posts from this blog

Why does Go error when trying to marshal this JSON? -

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

python - Pygame. TypeError: 'pygame.Surface' object is not callable -