How to create union of two different django-models?












0















I have two django-models



class ModelA(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_a')
other_column = models.CharField(/*...*/ db_column='other_column_a')


class ModelB(models.Model):
title = models.CharField(..., db_column='title')
text_a = models.CharField(..., db_column='text_b')
other_column = None


Then I want to merge the two querysets of this models using union



ModelA.objects.all().union(ModelB.objects.all())


But in query I see



(SELECT
`model_a`.`title`,
`model_a`.`text_a`,
`model_a`.`other_column`
FROM `model_a`)

UNION
(SELECT
`model_b`.`title`,
`model_b`.`text_b`
FROM `model_b`)


Of course I got the exception The used SELECT statements have a different number of columns.



How to create the aliases and fake columns to use union-query?










share|improve this question



























    0















    I have two django-models



    class ModelA(models.Model):
    title = models.CharField(..., db_column='title')
    text_a = models.CharField(..., db_column='text_a')
    other_column = models.CharField(/*...*/ db_column='other_column_a')


    class ModelB(models.Model):
    title = models.CharField(..., db_column='title')
    text_a = models.CharField(..., db_column='text_b')
    other_column = None


    Then I want to merge the two querysets of this models using union



    ModelA.objects.all().union(ModelB.objects.all())


    But in query I see



    (SELECT
    `model_a`.`title`,
    `model_a`.`text_a`,
    `model_a`.`other_column`
    FROM `model_a`)

    UNION
    (SELECT
    `model_b`.`title`,
    `model_b`.`text_b`
    FROM `model_b`)


    Of course I got the exception The used SELECT statements have a different number of columns.



    How to create the aliases and fake columns to use union-query?










    share|improve this question

























      0












      0








      0


      1






      I have two django-models



      class ModelA(models.Model):
      title = models.CharField(..., db_column='title')
      text_a = models.CharField(..., db_column='text_a')
      other_column = models.CharField(/*...*/ db_column='other_column_a')


      class ModelB(models.Model):
      title = models.CharField(..., db_column='title')
      text_a = models.CharField(..., db_column='text_b')
      other_column = None


      Then I want to merge the two querysets of this models using union



      ModelA.objects.all().union(ModelB.objects.all())


      But in query I see



      (SELECT
      `model_a`.`title`,
      `model_a`.`text_a`,
      `model_a`.`other_column`
      FROM `model_a`)

      UNION
      (SELECT
      `model_b`.`title`,
      `model_b`.`text_b`
      FROM `model_b`)


      Of course I got the exception The used SELECT statements have a different number of columns.



      How to create the aliases and fake columns to use union-query?










      share|improve this question














      I have two django-models



      class ModelA(models.Model):
      title = models.CharField(..., db_column='title')
      text_a = models.CharField(..., db_column='text_a')
      other_column = models.CharField(/*...*/ db_column='other_column_a')


      class ModelB(models.Model):
      title = models.CharField(..., db_column='title')
      text_a = models.CharField(..., db_column='text_b')
      other_column = None


      Then I want to merge the two querysets of this models using union



      ModelA.objects.all().union(ModelB.objects.all())


      But in query I see



      (SELECT
      `model_a`.`title`,
      `model_a`.`text_a`,
      `model_a`.`other_column`
      FROM `model_a`)

      UNION
      (SELECT
      `model_b`.`title`,
      `model_b`.`text_b`
      FROM `model_b`)


      Of course I got the exception The used SELECT statements have a different number of columns.



      How to create the aliases and fake columns to use union-query?







      mysql django django-models union






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 27 '18 at 8:55









      DmitryDmitry

      197217




      197217
























          2 Answers
          2






          active

          oldest

          votes


















          0














          In SQL query, we can use NULL to define the remaining columns/aliases



          (SELECT
          `model_a`.`title`,
          `model_a`.`text_a`,
          `model_a`.`other_column`
          FROM `model_a`)

          UNION

          (SELECT
          `model_b`.`title`,
          `model_b`.`text_b`,
          NULL
          FROM `model_b`)





          share|improve this answer
























          • Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

            – Dmitry
            Nov 27 '18 at 9:34













          • @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

            – Madhur Bhaiya
            Nov 27 '18 at 9:42



















          0














          In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:



          qsa = ModelA.objects.all().values('text_a', 'title')
          qsb = ModelB.objects.all().values('text_a', 'title')

          qsa.union(qsb)


          But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.



          First One, add an extra field in your Model with name other_column. You can put the values empty like this:



          other_column = models.CharField(max_length=255, null=True, default=None)


          and use the Django queryset union operations as described in here.



          Last One, the approach is bit pythonic. Try like this:



          a = ModelA.objects.values_list('text_a', 'title', 'other_column')
          b = ModelB.objects.values_list('text_a', 'title')

          union_list = list()

          for i in range(0, len(a)):
          if b[i] not in a[i]:
          union_list.append(b[i])
          union_list.append(a[i])


          Hope it helps!!






          share|improve this answer























            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%2f53495873%2fhow-to-create-union-of-two-different-django-models%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            In SQL query, we can use NULL to define the remaining columns/aliases



            (SELECT
            `model_a`.`title`,
            `model_a`.`text_a`,
            `model_a`.`other_column`
            FROM `model_a`)

            UNION

            (SELECT
            `model_b`.`title`,
            `model_b`.`text_b`,
            NULL
            FROM `model_b`)





            share|improve this answer
























            • Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

              – Dmitry
              Nov 27 '18 at 9:34













            • @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

              – Madhur Bhaiya
              Nov 27 '18 at 9:42
















            0














            In SQL query, we can use NULL to define the remaining columns/aliases



            (SELECT
            `model_a`.`title`,
            `model_a`.`text_a`,
            `model_a`.`other_column`
            FROM `model_a`)

            UNION

            (SELECT
            `model_b`.`title`,
            `model_b`.`text_b`,
            NULL
            FROM `model_b`)





            share|improve this answer
























            • Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

              – Dmitry
              Nov 27 '18 at 9:34













            • @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

              – Madhur Bhaiya
              Nov 27 '18 at 9:42














            0












            0








            0







            In SQL query, we can use NULL to define the remaining columns/aliases



            (SELECT
            `model_a`.`title`,
            `model_a`.`text_a`,
            `model_a`.`other_column`
            FROM `model_a`)

            UNION

            (SELECT
            `model_b`.`title`,
            `model_b`.`text_b`,
            NULL
            FROM `model_b`)





            share|improve this answer













            In SQL query, we can use NULL to define the remaining columns/aliases



            (SELECT
            `model_a`.`title`,
            `model_a`.`text_a`,
            `model_a`.`other_column`
            FROM `model_a`)

            UNION

            (SELECT
            `model_b`.`title`,
            `model_b`.`text_b`,
            NULL
            FROM `model_b`)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 27 '18 at 8:56









            Madhur BhaiyaMadhur Bhaiya

            19.6k62236




            19.6k62236













            • Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

              – Dmitry
              Nov 27 '18 at 9:34













            • @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

              – Madhur Bhaiya
              Nov 27 '18 at 9:42



















            • Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

              – Dmitry
              Nov 27 '18 at 9:34













            • @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

              – Madhur Bhaiya
              Nov 27 '18 at 9:42

















            Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

            – Dmitry
            Nov 27 '18 at 9:34







            Thanks for answer. I know how use union in mysql. I want to know how to describe it in django-models

            – Dmitry
            Nov 27 '18 at 9:34















            @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

            – Madhur Bhaiya
            Nov 27 '18 at 9:42





            @Dmitry I dont have much experience with Django. But based on some searches, you can use Value() or annotate(). check this answer: stackoverflow.com/a/52858358/2469308 and stackoverflow.com/a/34755617/2469308

            – Madhur Bhaiya
            Nov 27 '18 at 9:42













            0














            In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:



            qsa = ModelA.objects.all().values('text_a', 'title')
            qsb = ModelB.objects.all().values('text_a', 'title')

            qsa.union(qsb)


            But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.



            First One, add an extra field in your Model with name other_column. You can put the values empty like this:



            other_column = models.CharField(max_length=255, null=True, default=None)


            and use the Django queryset union operations as described in here.



            Last One, the approach is bit pythonic. Try like this:



            a = ModelA.objects.values_list('text_a', 'title', 'other_column')
            b = ModelB.objects.values_list('text_a', 'title')

            union_list = list()

            for i in range(0, len(a)):
            if b[i] not in a[i]:
            union_list.append(b[i])
            union_list.append(a[i])


            Hope it helps!!






            share|improve this answer




























              0














              In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:



              qsa = ModelA.objects.all().values('text_a', 'title')
              qsb = ModelB.objects.all().values('text_a', 'title')

              qsa.union(qsb)


              But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.



              First One, add an extra field in your Model with name other_column. You can put the values empty like this:



              other_column = models.CharField(max_length=255, null=True, default=None)


              and use the Django queryset union operations as described in here.



              Last One, the approach is bit pythonic. Try like this:



              a = ModelA.objects.values_list('text_a', 'title', 'other_column')
              b = ModelB.objects.values_list('text_a', 'title')

              union_list = list()

              for i in range(0, len(a)):
              if b[i] not in a[i]:
              union_list.append(b[i])
              union_list.append(a[i])


              Hope it helps!!






              share|improve this answer


























                0












                0








                0







                In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:



                qsa = ModelA.objects.all().values('text_a', 'title')
                qsb = ModelB.objects.all().values('text_a', 'title')

                qsa.union(qsb)


                But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.



                First One, add an extra field in your Model with name other_column. You can put the values empty like this:



                other_column = models.CharField(max_length=255, null=True, default=None)


                and use the Django queryset union operations as described in here.



                Last One, the approach is bit pythonic. Try like this:



                a = ModelA.objects.values_list('text_a', 'title', 'other_column')
                b = ModelB.objects.values_list('text_a', 'title')

                union_list = list()

                for i in range(0, len(a)):
                if b[i] not in a[i]:
                union_list.append(b[i])
                union_list.append(a[i])


                Hope it helps!!






                share|improve this answer













                In Django, union operations needs to have same columns, so with values_list you can use those specific columns only like this:



                qsa = ModelA.objects.all().values('text_a', 'title')
                qsb = ModelB.objects.all().values('text_a', 'title')

                qsa.union(qsb)


                But there is no way(that I know of) to mimic NULL in union in Django. So there are two ways you can proceed here.



                First One, add an extra field in your Model with name other_column. You can put the values empty like this:



                other_column = models.CharField(max_length=255, null=True, default=None)


                and use the Django queryset union operations as described in here.



                Last One, the approach is bit pythonic. Try like this:



                a = ModelA.objects.values_list('text_a', 'title', 'other_column')
                b = ModelB.objects.values_list('text_a', 'title')

                union_list = list()

                for i in range(0, len(a)):
                if b[i] not in a[i]:
                union_list.append(b[i])
                union_list.append(a[i])


                Hope it helps!!







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 28 '18 at 19:03









                ruddraruddra

                14.9k32748




                14.9k32748






























                    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%2f53495873%2fhow-to-create-union-of-two-different-django-models%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

                    Lallio

                    Unable to find Lightning Node

                    Futebolista