Django: Find all values in a ManyToMany relationship where all elements of the related set match certain criteria The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceWhere can I find the error logs of nginx, using fastcgi and djangoDjango removing object from ManyToMany relationshipHow to save a django model with a manyToMany Through relationship, AND regular manyToMany relationshipsDjango: ManyToMany filter matching on ALL items in a listWhat is wrong with my models.py?Django ManyToMany relation contains valueCreate a new model which have all fields of currently existing modelDjango manytomany: get all elements of all setsFilter a ManyToMany relationship to find items that have multiple matching relationsDjango How To Query ManyToMany Relationship Where All Objects Match

University's motivation for having tenure-track positions

How to politely respond to generic emails requesting a PhD/job in my lab? Without wasting too much time

Why is the object placed in the middle of the sentence here?

Semisimplicity of the category of coherent sheaves?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

Why did all the guest students take carriages to the Yule Ball?

How is simplicity better than precision and clarity in prose?

Is every episode of "Where are my Pants?" identical?

Take groceries in checked luggage

Single author papers against my advisor's will?

Did God make two great lights or did He make the great light two?

Format single node in tikzcd

Typeface like Times New Roman but with "tied" percent sign

Do working physicists consider Newtonian mechanics to be "falsified"?

Is there a writing software that you can sort scenes like slides in PowerPoint?

The variadic template constructor of my class cannot modify my class members, why is that so?

Reference for the teaching of not-self

Can a novice safely splice in wire to lengthen 5V charging cable?

Are my PIs rude or am I just being too sensitive?

Road tyres vs "Street" tyres for charity ride on MTB Tandem

Can withdrawing asylum be illegal?

Does Parliament need to approve the new Brexit delay to 31 October 2019?

how can a perfect fourth interval be considered either consonant or dissonant?

Can the DM override racial traits?



Django: Find all values in a ManyToMany relationship where all elements of the related set match certain criteria



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceWhere can I find the error logs of nginx, using fastcgi and djangoDjango removing object from ManyToMany relationshipHow to save a django model with a manyToMany Through relationship, AND regular manyToMany relationshipsDjango: ManyToMany filter matching on ALL items in a listWhat is wrong with my models.py?Django ManyToMany relation contains valueCreate a new model which have all fields of currently existing modelDjango manytomany: get all elements of all setsFilter a ManyToMany relationship to find items that have multiple matching relationsDjango How To Query ManyToMany Relationship Where All Objects Match



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








3















I have two models in a ManyToMany relationship. I want to get a subset of the first model for which every related model matches certain criteria.



Scenario: This is for a collaborative dictionary. A Word may have 0 or more Definitions. A Definition may be in a number of states: "complete", "in progress" or "abandoned". I am interested in finding all Words which have either no Definitions or only have "abandoned" Definitions.



class DefinitionState(Enum):
COMPLETE = 0
IN_PROGRESS = 1
ABANDONED = 2

class Definition(models.Model):
text = models.TextField()
status = models.IntegerField()

class Word(models.Model):
text = models.CharField(length=60)
definitions = models.ManyToManyField(Definition, related="words")

spam = Word.objects.create(text="spam")
eggs = Word.objects.create(text="eggs")
bacon = Word.objects.create(text="bacon")
lobster = Word.objects.create(text="lobster")

spam_d1 = Definition.objects.create(
text="Processed meat",
status=DefinitionState.COMPLETE
)
spam_d2 = Definition.objects.create(
text="Unwanted email",
status=DefinitionState.ABANDONED
)
spam.definitions.add(spam_d1)
spam.definitions.add(spam_d2)

eggs_d = Definition.objects.create(
text="Laid by chickens",
status=DefinitionState.COMPLETE
)
eggs.definitions.add(eggs_d)

bacon_d = Definition.objects.create(
text="Part of a pig",
status=DefinitionState.ABANDONED
)
bacon.definitions.add(bacon_d)


So I have four Words:




  • spam, which has one COMPLETE definition and one ABANDONED definition;


  • eggs, which has one COMPLETE definition;


  • bacon, which has one ABANDONED definition;


  • lobster, which has no definitions.

I want to write a query which will return (bacon, lobster) (in no particular order).



I can write the query to return lobster:



Word.objects.annotate(Count("definitions")).filter(definitions__count=0)


and I can identify which definitions are abandoned:



Definition.objects.filter(status=DefinitionState.ABANDONED)


but I can't figure out how to ask for Words whose Definitions are all ABANDONED.



Many thanks in advance










share|improve this question




























    3















    I have two models in a ManyToMany relationship. I want to get a subset of the first model for which every related model matches certain criteria.



    Scenario: This is for a collaborative dictionary. A Word may have 0 or more Definitions. A Definition may be in a number of states: "complete", "in progress" or "abandoned". I am interested in finding all Words which have either no Definitions or only have "abandoned" Definitions.



    class DefinitionState(Enum):
    COMPLETE = 0
    IN_PROGRESS = 1
    ABANDONED = 2

    class Definition(models.Model):
    text = models.TextField()
    status = models.IntegerField()

    class Word(models.Model):
    text = models.CharField(length=60)
    definitions = models.ManyToManyField(Definition, related="words")

    spam = Word.objects.create(text="spam")
    eggs = Word.objects.create(text="eggs")
    bacon = Word.objects.create(text="bacon")
    lobster = Word.objects.create(text="lobster")

    spam_d1 = Definition.objects.create(
    text="Processed meat",
    status=DefinitionState.COMPLETE
    )
    spam_d2 = Definition.objects.create(
    text="Unwanted email",
    status=DefinitionState.ABANDONED
    )
    spam.definitions.add(spam_d1)
    spam.definitions.add(spam_d2)

    eggs_d = Definition.objects.create(
    text="Laid by chickens",
    status=DefinitionState.COMPLETE
    )
    eggs.definitions.add(eggs_d)

    bacon_d = Definition.objects.create(
    text="Part of a pig",
    status=DefinitionState.ABANDONED
    )
    bacon.definitions.add(bacon_d)


    So I have four Words:




    • spam, which has one COMPLETE definition and one ABANDONED definition;


    • eggs, which has one COMPLETE definition;


    • bacon, which has one ABANDONED definition;


    • lobster, which has no definitions.

    I want to write a query which will return (bacon, lobster) (in no particular order).



    I can write the query to return lobster:



    Word.objects.annotate(Count("definitions")).filter(definitions__count=0)


    and I can identify which definitions are abandoned:



    Definition.objects.filter(status=DefinitionState.ABANDONED)


    but I can't figure out how to ask for Words whose Definitions are all ABANDONED.



    Many thanks in advance










    share|improve this question
























      3












      3








      3








      I have two models in a ManyToMany relationship. I want to get a subset of the first model for which every related model matches certain criteria.



      Scenario: This is for a collaborative dictionary. A Word may have 0 or more Definitions. A Definition may be in a number of states: "complete", "in progress" or "abandoned". I am interested in finding all Words which have either no Definitions or only have "abandoned" Definitions.



      class DefinitionState(Enum):
      COMPLETE = 0
      IN_PROGRESS = 1
      ABANDONED = 2

      class Definition(models.Model):
      text = models.TextField()
      status = models.IntegerField()

      class Word(models.Model):
      text = models.CharField(length=60)
      definitions = models.ManyToManyField(Definition, related="words")

      spam = Word.objects.create(text="spam")
      eggs = Word.objects.create(text="eggs")
      bacon = Word.objects.create(text="bacon")
      lobster = Word.objects.create(text="lobster")

      spam_d1 = Definition.objects.create(
      text="Processed meat",
      status=DefinitionState.COMPLETE
      )
      spam_d2 = Definition.objects.create(
      text="Unwanted email",
      status=DefinitionState.ABANDONED
      )
      spam.definitions.add(spam_d1)
      spam.definitions.add(spam_d2)

      eggs_d = Definition.objects.create(
      text="Laid by chickens",
      status=DefinitionState.COMPLETE
      )
      eggs.definitions.add(eggs_d)

      bacon_d = Definition.objects.create(
      text="Part of a pig",
      status=DefinitionState.ABANDONED
      )
      bacon.definitions.add(bacon_d)


      So I have four Words:




      • spam, which has one COMPLETE definition and one ABANDONED definition;


      • eggs, which has one COMPLETE definition;


      • bacon, which has one ABANDONED definition;


      • lobster, which has no definitions.

      I want to write a query which will return (bacon, lobster) (in no particular order).



      I can write the query to return lobster:



      Word.objects.annotate(Count("definitions")).filter(definitions__count=0)


      and I can identify which definitions are abandoned:



      Definition.objects.filter(status=DefinitionState.ABANDONED)


      but I can't figure out how to ask for Words whose Definitions are all ABANDONED.



      Many thanks in advance










      share|improve this question














      I have two models in a ManyToMany relationship. I want to get a subset of the first model for which every related model matches certain criteria.



      Scenario: This is for a collaborative dictionary. A Word may have 0 or more Definitions. A Definition may be in a number of states: "complete", "in progress" or "abandoned". I am interested in finding all Words which have either no Definitions or only have "abandoned" Definitions.



      class DefinitionState(Enum):
      COMPLETE = 0
      IN_PROGRESS = 1
      ABANDONED = 2

      class Definition(models.Model):
      text = models.TextField()
      status = models.IntegerField()

      class Word(models.Model):
      text = models.CharField(length=60)
      definitions = models.ManyToManyField(Definition, related="words")

      spam = Word.objects.create(text="spam")
      eggs = Word.objects.create(text="eggs")
      bacon = Word.objects.create(text="bacon")
      lobster = Word.objects.create(text="lobster")

      spam_d1 = Definition.objects.create(
      text="Processed meat",
      status=DefinitionState.COMPLETE
      )
      spam_d2 = Definition.objects.create(
      text="Unwanted email",
      status=DefinitionState.ABANDONED
      )
      spam.definitions.add(spam_d1)
      spam.definitions.add(spam_d2)

      eggs_d = Definition.objects.create(
      text="Laid by chickens",
      status=DefinitionState.COMPLETE
      )
      eggs.definitions.add(eggs_d)

      bacon_d = Definition.objects.create(
      text="Part of a pig",
      status=DefinitionState.ABANDONED
      )
      bacon.definitions.add(bacon_d)


      So I have four Words:




      • spam, which has one COMPLETE definition and one ABANDONED definition;


      • eggs, which has one COMPLETE definition;


      • bacon, which has one ABANDONED definition;


      • lobster, which has no definitions.

      I want to write a query which will return (bacon, lobster) (in no particular order).



      I can write the query to return lobster:



      Word.objects.annotate(Count("definitions")).filter(definitions__count=0)


      and I can identify which definitions are abandoned:



      Definition.objects.filter(status=DefinitionState.ABANDONED)


      but I can't figure out how to ask for Words whose Definitions are all ABANDONED.



      Many thanks in advance







      django many-to-many django-orm






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 13:33









      Neil PNeil P

      185




      185






















          1 Answer
          1






          active

          oldest

          votes


















          3














          Words.objects.exclude(definitions__status__in=[COMPLETE, IN_PROGRESS]) 





          share|improve this answer




















          • 1





            This would include Word objects that have no definitions at all, otherwise fine.

            – dyve
            Mar 8 at 14:00






          • 1





            Expected behavior. See 'lobster' example above

            – Nidal
            Mar 8 at 14:02






          • 1





            You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

            – dyve
            Mar 8 at 14:11






          • 1





            Sometimes you can't see the wood for the trees. Thanks @Nidal :)

            – Neil P
            Mar 8 at 14:26











          • It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

            – Neil P
            Mar 9 at 21:30












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064306%2fdjango-find-all-values-in-a-manytomany-relationship-where-all-elements-of-the-r%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          Words.objects.exclude(definitions__status__in=[COMPLETE, IN_PROGRESS]) 





          share|improve this answer




















          • 1





            This would include Word objects that have no definitions at all, otherwise fine.

            – dyve
            Mar 8 at 14:00






          • 1





            Expected behavior. See 'lobster' example above

            – Nidal
            Mar 8 at 14:02






          • 1





            You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

            – dyve
            Mar 8 at 14:11






          • 1





            Sometimes you can't see the wood for the trees. Thanks @Nidal :)

            – Neil P
            Mar 8 at 14:26











          • It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

            – Neil P
            Mar 9 at 21:30
















          3














          Words.objects.exclude(definitions__status__in=[COMPLETE, IN_PROGRESS]) 





          share|improve this answer




















          • 1





            This would include Word objects that have no definitions at all, otherwise fine.

            – dyve
            Mar 8 at 14:00






          • 1





            Expected behavior. See 'lobster' example above

            – Nidal
            Mar 8 at 14:02






          • 1





            You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

            – dyve
            Mar 8 at 14:11






          • 1





            Sometimes you can't see the wood for the trees. Thanks @Nidal :)

            – Neil P
            Mar 8 at 14:26











          • It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

            – Neil P
            Mar 9 at 21:30














          3












          3








          3







          Words.objects.exclude(definitions__status__in=[COMPLETE, IN_PROGRESS]) 





          share|improve this answer















          Words.objects.exclude(definitions__status__in=[COMPLETE, IN_PROGRESS]) 






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 14:03

























          answered Mar 8 at 13:54









          NidalNidal

          35029




          35029







          • 1





            This would include Word objects that have no definitions at all, otherwise fine.

            – dyve
            Mar 8 at 14:00






          • 1





            Expected behavior. See 'lobster' example above

            – Nidal
            Mar 8 at 14:02






          • 1





            You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

            – dyve
            Mar 8 at 14:11






          • 1





            Sometimes you can't see the wood for the trees. Thanks @Nidal :)

            – Neil P
            Mar 8 at 14:26











          • It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

            – Neil P
            Mar 9 at 21:30













          • 1





            This would include Word objects that have no definitions at all, otherwise fine.

            – dyve
            Mar 8 at 14:00






          • 1





            Expected behavior. See 'lobster' example above

            – Nidal
            Mar 8 at 14:02






          • 1





            You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

            – dyve
            Mar 8 at 14:11






          • 1





            Sometimes you can't see the wood for the trees. Thanks @Nidal :)

            – Neil P
            Mar 8 at 14:26











          • It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

            – Neil P
            Mar 9 at 21:30








          1




          1





          This would include Word objects that have no definitions at all, otherwise fine.

          – dyve
          Mar 8 at 14:00





          This would include Word objects that have no definitions at all, otherwise fine.

          – dyve
          Mar 8 at 14:00




          1




          1





          Expected behavior. See 'lobster' example above

          – Nidal
          Mar 8 at 14:02





          Expected behavior. See 'lobster' example above

          – Nidal
          Mar 8 at 14:02




          1




          1





          You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

          – dyve
          Mar 8 at 14:11





          You are right @Nidal. I'd already voted up your answer else I'd do it again :-)

          – dyve
          Mar 8 at 14:11




          1




          1





          Sometimes you can't see the wood for the trees. Thanks @Nidal :)

          – Neil P
          Mar 8 at 14:26





          Sometimes you can't see the wood for the trees. Thanks @Nidal :)

          – Neil P
          Mar 8 at 14:26













          It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

          – Neil P
          Mar 9 at 21:30






          It turned out that this solution became really slow (over 20 minutes) once I applied it to the real database, where I have over 108,000 Definitions and over 119,000 Words. 1627 Words needed to be returned from the query. I wound up putting an "abandoned" BooleanField on Word, which will be updated periodically and/or via a post_save signal on Definition.

          – Neil P
          Mar 9 at 21:30




















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064306%2fdjango-find-all-values-in-a-manytomany-relationship-where-all-elements-of-the-r%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved