Removing objects with many-to-many relationship

3,153 views
Skip to first unread message

rudy

unread,
Jul 30, 2009, 7:47:05 AM7/30/09
to Django users
Hello, everyone!

I'd like to remove some object with many-to-many relationship from
Django admin interface. Standard removing also removes all related
objects and the list of removed objects displayed on confirmation
page. But I don't need to remove related objects!

Assume we have ContentTopic and ContentItem:

class ContentTopic(models.Model):
name = models.CharField()
code = models.CharField()

class ContentItem(models.Model):
topic = models.ManyToManyField(ContentTopic, db_index=True,
blank=True, related_name='content_item')

So, I'd like to remove ContentTopic instance using Django admin, but I
don't need remove all related ContentItems. So, confirmation page
should display only ContentTopic instance to remove.

What is the best way to handle this?


Alexey Rudy

/////

Steve Schwarz

unread,
Jul 30, 2009, 8:10:54 AM7/30/09
to django...@googlegroups.com

Alexey,

I found this solution googling for "django one to many delete":
http://fragmentsofcode.wordpress.com/2009/03/06/django-gotcha-related-objects-deleted-by-default/

Best Regards,
Steve

Brian May

unread,
Jul 30, 2009, 9:55:54 PM7/30/09
to django...@googlegroups.com
On Thu, Jul 30, 2009 at 04:47:05AM -0700, rudy wrote:
> class ContentTopic(models.Model):
> name = models.CharField()
> code = models.CharField()
>
> class ContentItem(models.Model):
> topic = models.ManyToManyField(ContentTopic, db_index=True,
> blank=True, related_name='content_item')
>
> So, I'd like to remove ContentTopic instance using Django admin, but I
> don't need remove all related ContentItems. So, confirmation page
> should display only ContentTopic instance to remove.

My understanding (correct me if I am wrong) is it shouldn't be a problem with
many-to-many relationships.

When deleting a ContentTopic, Django will delete the entry from the mapping
table, and not touch ContentItem table. This is usually what you want - when
you delete the object you can't have the relationship anymore.

One-to-many relationships are a different story. You do have to be
careful here.
--
Brian May <br...@microcomaustralia.com.au>

Reply all
Reply to author
Forward
0 new messages