Django querying on model which is involved in generic relation












0














Here I have 2 models, Company and UserSupervision. Company is related as a foreign key with generic relation model UserSupervision.



I want to have a query as following:



Company.objects.filter(**{'usersupervision__content_type': Company,
'usersupervision__user': some_user,
'usersupervision__date_cancelled': None})


So, I want to get all companies of some_user appeared in UserSupervision model. I know that Company and UserSupervision are not directly related, so i thought, maybe i have to use raw sql with joins? Or any other more appropriate solution?



class Company(models.Model):
id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4)
name = models.CharField(max_length=150, unique=True)

users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership')
date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True)
date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True)


class UserSupervision(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True)

content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.UUIDField()
content_object = GenericForeignKey()

date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True)
date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None)









share|improve this question





























    0














    Here I have 2 models, Company and UserSupervision. Company is related as a foreign key with generic relation model UserSupervision.



    I want to have a query as following:



    Company.objects.filter(**{'usersupervision__content_type': Company,
    'usersupervision__user': some_user,
    'usersupervision__date_cancelled': None})


    So, I want to get all companies of some_user appeared in UserSupervision model. I know that Company and UserSupervision are not directly related, so i thought, maybe i have to use raw sql with joins? Or any other more appropriate solution?



    class Company(models.Model):
    id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4)
    name = models.CharField(max_length=150, unique=True)

    users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership')
    date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True)
    date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True)


    class UserSupervision(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField()
    content_object = GenericForeignKey()

    date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True)
    date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None)









    share|improve this question



























      0












      0








      0







      Here I have 2 models, Company and UserSupervision. Company is related as a foreign key with generic relation model UserSupervision.



      I want to have a query as following:



      Company.objects.filter(**{'usersupervision__content_type': Company,
      'usersupervision__user': some_user,
      'usersupervision__date_cancelled': None})


      So, I want to get all companies of some_user appeared in UserSupervision model. I know that Company and UserSupervision are not directly related, so i thought, maybe i have to use raw sql with joins? Or any other more appropriate solution?



      class Company(models.Model):
      id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4)
      name = models.CharField(max_length=150, unique=True)

      users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership')
      date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True)
      date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True)


      class UserSupervision(models.Model):
      user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
      supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True)

      content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
      object_id = models.UUIDField()
      content_object = GenericForeignKey()

      date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True)
      date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None)









      share|improve this question















      Here I have 2 models, Company and UserSupervision. Company is related as a foreign key with generic relation model UserSupervision.



      I want to have a query as following:



      Company.objects.filter(**{'usersupervision__content_type': Company,
      'usersupervision__user': some_user,
      'usersupervision__date_cancelled': None})


      So, I want to get all companies of some_user appeared in UserSupervision model. I know that Company and UserSupervision are not directly related, so i thought, maybe i have to use raw sql with joins? Or any other more appropriate solution?



      class Company(models.Model):
      id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4)
      name = models.CharField(max_length=150, unique=True)

      users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership')
      date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True)
      date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True)


      class UserSupervision(models.Model):
      user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
      supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True)

      content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
      object_id = models.UUIDField()
      content_object = GenericForeignKey()

      date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True)
      date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None)






      sql django django-models querying






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 '18 at 16:34









      Daniel Roseman

      444k41575631




      444k41575631










      asked Nov 19 '18 at 16:09









      Bedilbek

      82




      82
























          1 Answer
          1






          active

          oldest

          votes


















          0














          So you want to find all the Companies in UserSupervision for a certian UserSupervision.user? Something like:



          user_supervisions = UserSupervision.objects.filter(
          content_type=ContentType.objects.get_for_model(Company),
          user=some_user,
          date_cancelled=None
          ).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

          companies = [us.object_id for us in usersupervisions] # Loop to create list of company ids.


          You can drop the order_by and distinct if you're not using PostgreSQL, but the companies loop would need to be changed to account for duplicate entries.






          share|improve this answer





















          • Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
            – Bedilbek
            Nov 19 '18 at 17:49











          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%2f53378604%2fdjango-querying-on-model-which-is-involved-in-generic-relation%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









          0














          So you want to find all the Companies in UserSupervision for a certian UserSupervision.user? Something like:



          user_supervisions = UserSupervision.objects.filter(
          content_type=ContentType.objects.get_for_model(Company),
          user=some_user,
          date_cancelled=None
          ).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

          companies = [us.object_id for us in usersupervisions] # Loop to create list of company ids.


          You can drop the order_by and distinct if you're not using PostgreSQL, but the companies loop would need to be changed to account for duplicate entries.






          share|improve this answer





















          • Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
            – Bedilbek
            Nov 19 '18 at 17:49
















          0














          So you want to find all the Companies in UserSupervision for a certian UserSupervision.user? Something like:



          user_supervisions = UserSupervision.objects.filter(
          content_type=ContentType.objects.get_for_model(Company),
          user=some_user,
          date_cancelled=None
          ).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

          companies = [us.object_id for us in usersupervisions] # Loop to create list of company ids.


          You can drop the order_by and distinct if you're not using PostgreSQL, but the companies loop would need to be changed to account for duplicate entries.






          share|improve this answer





















          • Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
            – Bedilbek
            Nov 19 '18 at 17:49














          0












          0








          0






          So you want to find all the Companies in UserSupervision for a certian UserSupervision.user? Something like:



          user_supervisions = UserSupervision.objects.filter(
          content_type=ContentType.objects.get_for_model(Company),
          user=some_user,
          date_cancelled=None
          ).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

          companies = [us.object_id for us in usersupervisions] # Loop to create list of company ids.


          You can drop the order_by and distinct if you're not using PostgreSQL, but the companies loop would need to be changed to account for duplicate entries.






          share|improve this answer












          So you want to find all the Companies in UserSupervision for a certian UserSupervision.user? Something like:



          user_supervisions = UserSupervision.objects.filter(
          content_type=ContentType.objects.get_for_model(Company),
          user=some_user,
          date_cancelled=None
          ).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

          companies = [us.object_id for us in usersupervisions] # Loop to create list of company ids.


          You can drop the order_by and distinct if you're not using PostgreSQL, but the companies loop would need to be changed to account for duplicate entries.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 17:33









          Bott0610

          588211




          588211












          • Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
            – Bedilbek
            Nov 19 '18 at 17:49


















          • Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
            – Bedilbek
            Nov 19 '18 at 17:49
















          Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
          – Bedilbek
          Nov 19 '18 at 17:49




          Thanks for the reply, but I wanted to have querying method or raw-sql method, because, first fetching from database and again filtering with python is time and memory consuming job, I knew that i could do it with this kind of simple wrangling around, but it would be more concise and accurate if only one time querying with filtering is made, anyway thanks:)
          – Bedilbek
          Nov 19 '18 at 17:49


















          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%2f53378604%2fdjango-querying-on-model-which-is-involved-in-generic-relation%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

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith