#20686 closed New feature (wontfix)

Many-to-many related manager method: toggle()

Reported by: Deacalion Owned by:
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords: toggle
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

My use case: on a few occasions I've needed to ‘toggle’ an M2M relation between two models, i.e. if the relation exists, it should be removed and if it doesn't it should be created.

Usage – using these models:

>>> a4
    <Article: Oxygen-free diet works wonders>
>>> p2
    <Publication: Science News>
>>> p2.article_set.all()
    [
        <Article: NASA finds intelligent life on Earth>,
        <Article: NASA uses Python>,
        <Article: Oxygen-free diet works wonders>,
    ]
>>> a4.publications.toggle(p2) # the relation is removed
>>> p2.article_set.all()
    [
        <Article: NASA finds intelligent life on Earth>,
        <Article: NASA uses Python>,
    ]
>>> a4.publications.toggle(p2) # the relation is added
>>> p2.article_set.all()
    [
        <Article: NASA finds intelligent life on Earth>,
        <Article: NASA uses Python>,
        <Article: Oxygen-free diet works wonders>,
    ]
>>> p2.article_set.toggle(a4) # and… removed again (can be toggled from either model)
    [
        <Article: NASA finds intelligent life on Earth>,
        <Article: NASA uses Python>,
    ]

Change History (4)

comment:1 Changed 23 months ago by Deacalion

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Not reviewed yet, but here's the code if you decide to go ahead (I'll add documentation if it's accepted):

https://github.com/Matt-Stevens/django/commit/9b44c

Last edited 23 months ago by Deacalion (previous) (diff)

comment:2 Changed 23 months ago by Deacalion

  • Owner changed from nobody to Deacalion
  • Status changed from new to assigned

comment:3 Changed 23 months ago by Deacalion

  • Owner Deacalion deleted
  • Status changed from assigned to new

comment:4 Changed 22 months ago by akaariai

  • Resolution set to wontfix
  • Status changed from new to closed

My initial feeling is to not include this. I just don't see enough uses for this. On the other hand I don't have too many projects to use as basis for my opinion. So, I am not going to accept this one, but if it turns out there is a lot of demand for this then lets re-review this. The DevelopersMailingList is the right place to discuss this further.

Note: See TracTickets for help on using tickets.
Back to Top