many to many field django how to join









up vote
0
down vote

favorite












I have no previous experience with many to many fields in django. This is the first time I´m using it, so I´m getting a little confused here.
So, this is what I have:



#models.py
class RefereciaCita(models.Model):
titulo = models.CharField(max_length=500, null=True, blank=True, help_text='título da pesquisa')
link = models.URLField(blank=True, null=True, help_text='link da pesquisa')
#pesquisador = models.ForeignKey('AutorPesquisa',null=True, blank=True,
#help_text='pesquisadores que participam da pesquisa', on_delete=models.SET_NULL)
pesq = models.ManyToManyField('AutoresPesq', related_name='autoresDaPesquisa',through='AutorRef', verbose_name='pesquisador')
def __str__(self):
return self.titulo
class Meta:
verbose_name = "Referência bibliográfica"
verbose_name_plural = "Referências bibliográficas"


class AutoresPesq(models.Model):
nome = models.CharField(max_length=500, null=True, blank=True, help_text='nome do pesquisador')
link = models.URLField(blank=True, null=True, help_text='link do currículo do pesquisador')
pesquisa = models.ManyToManyField('RefereciaCita', through='AutorRef', verbose_name='pesquisador',
related_name='pesquisaDoAutor', help_text='pesquisa que o autor participa')

def __str__(self):
return self.nome
class Meta:
verbose_name = "Autores Pesquisa"
verbose_name_plural = "Autores Pesquisa"

class AutorRef(models.Model):
pesquisa = models.ForeignKey(RefereciaCita, null=True, related_name='pesquisarn',
help_text='pesquisa que o autor participa', on_delete=models.CASCADE)
pesquisador = models.ForeignKey(AutoresPesq, null=True, related_name='autorDaPesquisa',
help_text='pesquisadores que participam da pesquisa', on_delete=models.CASCADE)

def __str__(self):
return self.pesquisador.nome + ", " + self.pesquisa.titulo[:190]

class Meta:
verbose_name = "Autor Pesquisa"
verbose_name_plural = "Autor Pesquisa"


I need to retrive, from each ReferenciaCita it´s respective(s) AutoresPesq



So in the template I would have something like the picture



enter image description here



So, I need to get for each 'researchPaper' it´s 'author'



But I´m getting confused with the queryset´s...
I´ve already tried with select_related and prefetch_related,
but I´m missing something here...



The middle table goes like this



enter image description here



Please help, I´m really stuck here, and have no clues...










share|improve this question

























    up vote
    0
    down vote

    favorite












    I have no previous experience with many to many fields in django. This is the first time I´m using it, so I´m getting a little confused here.
    So, this is what I have:



    #models.py
    class RefereciaCita(models.Model):
    titulo = models.CharField(max_length=500, null=True, blank=True, help_text='título da pesquisa')
    link = models.URLField(blank=True, null=True, help_text='link da pesquisa')
    #pesquisador = models.ForeignKey('AutorPesquisa',null=True, blank=True,
    #help_text='pesquisadores que participam da pesquisa', on_delete=models.SET_NULL)
    pesq = models.ManyToManyField('AutoresPesq', related_name='autoresDaPesquisa',through='AutorRef', verbose_name='pesquisador')
    def __str__(self):
    return self.titulo
    class Meta:
    verbose_name = "Referência bibliográfica"
    verbose_name_plural = "Referências bibliográficas"


    class AutoresPesq(models.Model):
    nome = models.CharField(max_length=500, null=True, blank=True, help_text='nome do pesquisador')
    link = models.URLField(blank=True, null=True, help_text='link do currículo do pesquisador')
    pesquisa = models.ManyToManyField('RefereciaCita', through='AutorRef', verbose_name='pesquisador',
    related_name='pesquisaDoAutor', help_text='pesquisa que o autor participa')

    def __str__(self):
    return self.nome
    class Meta:
    verbose_name = "Autores Pesquisa"
    verbose_name_plural = "Autores Pesquisa"

    class AutorRef(models.Model):
    pesquisa = models.ForeignKey(RefereciaCita, null=True, related_name='pesquisarn',
    help_text='pesquisa que o autor participa', on_delete=models.CASCADE)
    pesquisador = models.ForeignKey(AutoresPesq, null=True, related_name='autorDaPesquisa',
    help_text='pesquisadores que participam da pesquisa', on_delete=models.CASCADE)

    def __str__(self):
    return self.pesquisador.nome + ", " + self.pesquisa.titulo[:190]

    class Meta:
    verbose_name = "Autor Pesquisa"
    verbose_name_plural = "Autor Pesquisa"


    I need to retrive, from each ReferenciaCita it´s respective(s) AutoresPesq



    So in the template I would have something like the picture



    enter image description here



    So, I need to get for each 'researchPaper' it´s 'author'



    But I´m getting confused with the queryset´s...
    I´ve already tried with select_related and prefetch_related,
    but I´m missing something here...



    The middle table goes like this



    enter image description here



    Please help, I´m really stuck here, and have no clues...










    share|improve this question























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have no previous experience with many to many fields in django. This is the first time I´m using it, so I´m getting a little confused here.
      So, this is what I have:



      #models.py
      class RefereciaCita(models.Model):
      titulo = models.CharField(max_length=500, null=True, blank=True, help_text='título da pesquisa')
      link = models.URLField(blank=True, null=True, help_text='link da pesquisa')
      #pesquisador = models.ForeignKey('AutorPesquisa',null=True, blank=True,
      #help_text='pesquisadores que participam da pesquisa', on_delete=models.SET_NULL)
      pesq = models.ManyToManyField('AutoresPesq', related_name='autoresDaPesquisa',through='AutorRef', verbose_name='pesquisador')
      def __str__(self):
      return self.titulo
      class Meta:
      verbose_name = "Referência bibliográfica"
      verbose_name_plural = "Referências bibliográficas"


      class AutoresPesq(models.Model):
      nome = models.CharField(max_length=500, null=True, blank=True, help_text='nome do pesquisador')
      link = models.URLField(blank=True, null=True, help_text='link do currículo do pesquisador')
      pesquisa = models.ManyToManyField('RefereciaCita', through='AutorRef', verbose_name='pesquisador',
      related_name='pesquisaDoAutor', help_text='pesquisa que o autor participa')

      def __str__(self):
      return self.nome
      class Meta:
      verbose_name = "Autores Pesquisa"
      verbose_name_plural = "Autores Pesquisa"

      class AutorRef(models.Model):
      pesquisa = models.ForeignKey(RefereciaCita, null=True, related_name='pesquisarn',
      help_text='pesquisa que o autor participa', on_delete=models.CASCADE)
      pesquisador = models.ForeignKey(AutoresPesq, null=True, related_name='autorDaPesquisa',
      help_text='pesquisadores que participam da pesquisa', on_delete=models.CASCADE)

      def __str__(self):
      return self.pesquisador.nome + ", " + self.pesquisa.titulo[:190]

      class Meta:
      verbose_name = "Autor Pesquisa"
      verbose_name_plural = "Autor Pesquisa"


      I need to retrive, from each ReferenciaCita it´s respective(s) AutoresPesq



      So in the template I would have something like the picture



      enter image description here



      So, I need to get for each 'researchPaper' it´s 'author'



      But I´m getting confused with the queryset´s...
      I´ve already tried with select_related and prefetch_related,
      but I´m missing something here...



      The middle table goes like this



      enter image description here



      Please help, I´m really stuck here, and have no clues...










      share|improve this question













      I have no previous experience with many to many fields in django. This is the first time I´m using it, so I´m getting a little confused here.
      So, this is what I have:



      #models.py
      class RefereciaCita(models.Model):
      titulo = models.CharField(max_length=500, null=True, blank=True, help_text='título da pesquisa')
      link = models.URLField(blank=True, null=True, help_text='link da pesquisa')
      #pesquisador = models.ForeignKey('AutorPesquisa',null=True, blank=True,
      #help_text='pesquisadores que participam da pesquisa', on_delete=models.SET_NULL)
      pesq = models.ManyToManyField('AutoresPesq', related_name='autoresDaPesquisa',through='AutorRef', verbose_name='pesquisador')
      def __str__(self):
      return self.titulo
      class Meta:
      verbose_name = "Referência bibliográfica"
      verbose_name_plural = "Referências bibliográficas"


      class AutoresPesq(models.Model):
      nome = models.CharField(max_length=500, null=True, blank=True, help_text='nome do pesquisador')
      link = models.URLField(blank=True, null=True, help_text='link do currículo do pesquisador')
      pesquisa = models.ManyToManyField('RefereciaCita', through='AutorRef', verbose_name='pesquisador',
      related_name='pesquisaDoAutor', help_text='pesquisa que o autor participa')

      def __str__(self):
      return self.nome
      class Meta:
      verbose_name = "Autores Pesquisa"
      verbose_name_plural = "Autores Pesquisa"

      class AutorRef(models.Model):
      pesquisa = models.ForeignKey(RefereciaCita, null=True, related_name='pesquisarn',
      help_text='pesquisa que o autor participa', on_delete=models.CASCADE)
      pesquisador = models.ForeignKey(AutoresPesq, null=True, related_name='autorDaPesquisa',
      help_text='pesquisadores que participam da pesquisa', on_delete=models.CASCADE)

      def __str__(self):
      return self.pesquisador.nome + ", " + self.pesquisa.titulo[:190]

      class Meta:
      verbose_name = "Autor Pesquisa"
      verbose_name_plural = "Autor Pesquisa"


      I need to retrive, from each ReferenciaCita it´s respective(s) AutoresPesq



      So in the template I would have something like the picture



      enter image description here



      So, I need to get for each 'researchPaper' it´s 'author'



      But I´m getting confused with the queryset´s...
      I´ve already tried with select_related and prefetch_related,
      but I´m missing something here...



      The middle table goes like this



      enter image description here



      Please help, I´m really stuck here, and have no clues...







      django django-queryset jointable






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 18:57









      Adriel Werlich

      4319




      4319






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          For your first question, you can do:



          qs_referencia_cita = ReferenciaCita.objects.all() # All ReferenciaCita

          for referencia_cita in qs_referencia_cita:
          for autores_pesq in referencia_cita.pesq.all():
          # Use your autores_pesq


          The rest is unclear what's you're asking.



          PS: You don't need both relations as ManyToManyField: The other relation is created automatically, see this part of the doc.






          share|improve this answer






















          • yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
            – Adriel Werlich
            Nov 11 at 19:28











          • for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
            – Adriel Werlich
            Nov 11 at 19:29










          • Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
            – Cyrlop
            Nov 11 at 19:40










          • Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
            – Adriel Werlich
            Nov 11 at 20:15











          • Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
            – Cyrlop
            Nov 14 at 15:47










          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',
          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%2f53252102%2fmany-to-many-field-django-how-to-join%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








          up vote
          1
          down vote



          accepted










          For your first question, you can do:



          qs_referencia_cita = ReferenciaCita.objects.all() # All ReferenciaCita

          for referencia_cita in qs_referencia_cita:
          for autores_pesq in referencia_cita.pesq.all():
          # Use your autores_pesq


          The rest is unclear what's you're asking.



          PS: You don't need both relations as ManyToManyField: The other relation is created automatically, see this part of the doc.






          share|improve this answer






















          • yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
            – Adriel Werlich
            Nov 11 at 19:28











          • for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
            – Adriel Werlich
            Nov 11 at 19:29










          • Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
            – Cyrlop
            Nov 11 at 19:40










          • Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
            – Adriel Werlich
            Nov 11 at 20:15











          • Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
            – Cyrlop
            Nov 14 at 15:47














          up vote
          1
          down vote



          accepted










          For your first question, you can do:



          qs_referencia_cita = ReferenciaCita.objects.all() # All ReferenciaCita

          for referencia_cita in qs_referencia_cita:
          for autores_pesq in referencia_cita.pesq.all():
          # Use your autores_pesq


          The rest is unclear what's you're asking.



          PS: You don't need both relations as ManyToManyField: The other relation is created automatically, see this part of the doc.






          share|improve this answer






















          • yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
            – Adriel Werlich
            Nov 11 at 19:28











          • for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
            – Adriel Werlich
            Nov 11 at 19:29










          • Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
            – Cyrlop
            Nov 11 at 19:40










          • Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
            – Adriel Werlich
            Nov 11 at 20:15











          • Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
            – Cyrlop
            Nov 14 at 15:47












          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          For your first question, you can do:



          qs_referencia_cita = ReferenciaCita.objects.all() # All ReferenciaCita

          for referencia_cita in qs_referencia_cita:
          for autores_pesq in referencia_cita.pesq.all():
          # Use your autores_pesq


          The rest is unclear what's you're asking.



          PS: You don't need both relations as ManyToManyField: The other relation is created automatically, see this part of the doc.






          share|improve this answer














          For your first question, you can do:



          qs_referencia_cita = ReferenciaCita.objects.all() # All ReferenciaCita

          for referencia_cita in qs_referencia_cita:
          for autores_pesq in referencia_cita.pesq.all():
          # Use your autores_pesq


          The rest is unclear what's you're asking.



          PS: You don't need both relations as ManyToManyField: The other relation is created automatically, see this part of the doc.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 19:38

























          answered Nov 11 at 19:14









          Cyrlop

          1,3171818




          1,3171818











          • yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
            – Adriel Werlich
            Nov 11 at 19:28











          • for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
            – Adriel Werlich
            Nov 11 at 19:29










          • Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
            – Cyrlop
            Nov 11 at 19:40










          • Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
            – Adriel Werlich
            Nov 11 at 20:15











          • Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
            – Cyrlop
            Nov 14 at 15:47
















          • yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
            – Adriel Werlich
            Nov 11 at 19:28











          • for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
            – Adriel Werlich
            Nov 11 at 19:29










          • Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
            – Cyrlop
            Nov 11 at 19:40










          • Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
            – Adriel Werlich
            Nov 11 at 20:15











          • Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
            – Cyrlop
            Nov 14 at 15:47















          yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
          – Adriel Werlich
          Nov 11 at 19:28





          yes, thanks for the help... I´ve did like your example, but returned the following 'RefereciaCita' object has no attribute 'autorespesq_set'
          – Adriel Werlich
          Nov 11 at 19:28













          for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
          – Adriel Werlich
          Nov 11 at 19:29




          for rf in referencias: for au in rf.autorespesq_set.all(): print(au)
          – Adriel Werlich
          Nov 11 at 19:29












          Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
          – Cyrlop
          Nov 11 at 19:40




          Edited my answer, I didn't see you had two m2m relation, that is not needed. You can use ` rf.pesq.all()` in your case, rf.pesq is an object manager.
          – Cyrlop
          Nov 11 at 19:40












          Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
          – Adriel Werlich
          Nov 11 at 20:15





          Yes,@Cyrlop, that worked ... thanks a lot for your help... I was really confused about this, because I´ve never used this feature before.... thanks again!
          – Adriel Werlich
          Nov 11 at 20:15













          Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
          – Cyrlop
          Nov 14 at 15:47




          Glad it fixed your problem, feel free to accept the answer if this particular issue is solved.
          – Cyrlop
          Nov 14 at 15:47

















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53252102%2fmany-to-many-field-django-how-to-join%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







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

          Museum of Modern and Contemporary Art of Trento and Rovereto