Django - Performing a subquery on a subquery and then getting all associated fields Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Django - return all associated rows for distinct results set with postgres backendExtending the User model with custom fields in DjangoIn a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?How can I get the full/absolute URL (with domain) in Django?How to get the current URL within a Django template?Django: Get list of model fields?Get model's fields in DjangoGetting the SQL from a Django QuerySetHow to perform OR condition in django queryset?Convert Django Model object to dict with all of the fields intactDjango - return all associated rows for distinct results set with postgres backend

Is CEO the profession with the most psychopaths?

An adverb for when you're not exaggerating

Around usage results

Is it ethical to give a final exam after the professor has quit before teaching the remaining chapters of the course?

Can anything be seen from the center of the Boötes void? How dark would it be?

What is homebrew?

Maximum summed powersets with non-adjacent items

Why didn't Eitri join the fight?

What's the meaning of "fortified infraction restraint"?

How do I stop a creek from eroding my steep embankment?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

Circuit to "zoom in" on mV fluctuations of a DC signal?

Dating a Former Employee

How do I find out the mythology and history of my Fortress?

How to Make a Beautiful Stacked 3D Plot

Using audio cues to encourage good posture

Compare a given version number in the form major.minor.build.patch and see if one is less than the other

How do I make this wiring inside cabinet safer? (Pic)

Wu formula for manifolds with boundary

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Do jazz musicians improvise on the parent scale in addition to the chord-scales?

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

How do pianists reach extremely loud dynamics?



Django - Performing a subquery on a subquery and then getting all associated fields



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Django - return all associated rows for distinct results set with postgres backendExtending the User model with custom fields in DjangoIn a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?How can I get the full/absolute URL (with domain) in Django?How to get the current URL within a Django template?Django: Get list of model fields?Get model's fields in DjangoGetting the SQL from a Django QuerySetHow to perform OR condition in django queryset?Convert Django Model object to dict with all of the fields intactDjango - return all associated rows for distinct results set with postgres backend



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








0















I have data in the following form:



collection_name | type | manufacturer | description | image_url
---------------------------------------------------------------------------
beach | bed | company a | nice bed | 1.jpg
beach | king bed | company a | nice bed | 1.jpg
beach | nightstand | company a | nice ns | 1.jpg
grass | chest | company a | nice chest | 2.jpg
apple | chest | company a | nice chest | 3.jpg
fiver | chest | company b | good chest | 4.jpg


and models like:



class Product(models.Model):
collection_name = models.TextField(null='true',blank='true')
type = models.TextField(null='true',blank='true')
manufacturer = models.TextField(null='true',blank='true')
description = models.TextField(null='true',blank='true')
image_url = models.TextField(null='true',blank='true')


What am I trying to do in my app at the moment is:



  • Link to a product by id (using the hidden pk id field),

  • Then for that id get the collection name

  • Get a list of products with that collection name

  • Get a list of distinct image_urls from the set of products with a certain collection name *

  • for each image_url in the new set, get all records that have the same image_url

The reason I want to do this, is as you can see in the above sample data, different products sometimes reuse the same image (some images show multiple products in one image). I want to show each image only once, while being able to show all products associated with a given image (of which there could be multiple).



I've been thinking to do something like the following based on this answer, which I think follows the logic given above, but I'm not sure it is the correct approach.



collectionname = product.objects.filter(id=id).values('collection_name').distinct()
images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
results = []
for img in images:
pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
obj = "image": img['image_url'], "items":["attr":pbi.attr, ... for pbi in pbis]
results.append(obj)


What are the obvious errors in my approach here, and is there a better, cleaner way to do this? In case it is relevant, the backend is postgres.



What I would like to be able to do in the template is something like:



% for instance in image_url %
collection_name Collection:
<img src=" instance ">
Product type: instance.type
Product Description: instance.description
% endfor %


Which should output something like:



For 1.jpg:



Beach Collection
<img src="1.jpg">
Product type: bed
Product Description: nice bed
Product type: king bed
Product Description: nice bed
Product type: nightstand
Product Description: nice ns


For 2.jpg:



Grass Collection
<img src="2.jpg">
Product type: chest
Product Description: nice chest


For 3.jpg:



Apple Collection
<img src="3.jpg">
Product type: chest
Product Description: nice chest


For 4.jpg:



Fiver Collection
<img src="4.jpg">
Product type: chest
Product Description: good chest









share|improve this question




























    0















    I have data in the following form:



    collection_name | type | manufacturer | description | image_url
    ---------------------------------------------------------------------------
    beach | bed | company a | nice bed | 1.jpg
    beach | king bed | company a | nice bed | 1.jpg
    beach | nightstand | company a | nice ns | 1.jpg
    grass | chest | company a | nice chest | 2.jpg
    apple | chest | company a | nice chest | 3.jpg
    fiver | chest | company b | good chest | 4.jpg


    and models like:



    class Product(models.Model):
    collection_name = models.TextField(null='true',blank='true')
    type = models.TextField(null='true',blank='true')
    manufacturer = models.TextField(null='true',blank='true')
    description = models.TextField(null='true',blank='true')
    image_url = models.TextField(null='true',blank='true')


    What am I trying to do in my app at the moment is:



    • Link to a product by id (using the hidden pk id field),

    • Then for that id get the collection name

    • Get a list of products with that collection name

    • Get a list of distinct image_urls from the set of products with a certain collection name *

    • for each image_url in the new set, get all records that have the same image_url

    The reason I want to do this, is as you can see in the above sample data, different products sometimes reuse the same image (some images show multiple products in one image). I want to show each image only once, while being able to show all products associated with a given image (of which there could be multiple).



    I've been thinking to do something like the following based on this answer, which I think follows the logic given above, but I'm not sure it is the correct approach.



    collectionname = product.objects.filter(id=id).values('collection_name').distinct()
    images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
    results = []
    for img in images:
    pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
    obj = "image": img['image_url'], "items":["attr":pbi.attr, ... for pbi in pbis]
    results.append(obj)


    What are the obvious errors in my approach here, and is there a better, cleaner way to do this? In case it is relevant, the backend is postgres.



    What I would like to be able to do in the template is something like:



    % for instance in image_url %
    collection_name Collection:
    <img src=" instance ">
    Product type: instance.type
    Product Description: instance.description
    % endfor %


    Which should output something like:



    For 1.jpg:



    Beach Collection
    <img src="1.jpg">
    Product type: bed
    Product Description: nice bed
    Product type: king bed
    Product Description: nice bed
    Product type: nightstand
    Product Description: nice ns


    For 2.jpg:



    Grass Collection
    <img src="2.jpg">
    Product type: chest
    Product Description: nice chest


    For 3.jpg:



    Apple Collection
    <img src="3.jpg">
    Product type: chest
    Product Description: nice chest


    For 4.jpg:



    Fiver Collection
    <img src="4.jpg">
    Product type: chest
    Product Description: good chest









    share|improve this question
























      0












      0








      0








      I have data in the following form:



      collection_name | type | manufacturer | description | image_url
      ---------------------------------------------------------------------------
      beach | bed | company a | nice bed | 1.jpg
      beach | king bed | company a | nice bed | 1.jpg
      beach | nightstand | company a | nice ns | 1.jpg
      grass | chest | company a | nice chest | 2.jpg
      apple | chest | company a | nice chest | 3.jpg
      fiver | chest | company b | good chest | 4.jpg


      and models like:



      class Product(models.Model):
      collection_name = models.TextField(null='true',blank='true')
      type = models.TextField(null='true',blank='true')
      manufacturer = models.TextField(null='true',blank='true')
      description = models.TextField(null='true',blank='true')
      image_url = models.TextField(null='true',blank='true')


      What am I trying to do in my app at the moment is:



      • Link to a product by id (using the hidden pk id field),

      • Then for that id get the collection name

      • Get a list of products with that collection name

      • Get a list of distinct image_urls from the set of products with a certain collection name *

      • for each image_url in the new set, get all records that have the same image_url

      The reason I want to do this, is as you can see in the above sample data, different products sometimes reuse the same image (some images show multiple products in one image). I want to show each image only once, while being able to show all products associated with a given image (of which there could be multiple).



      I've been thinking to do something like the following based on this answer, which I think follows the logic given above, but I'm not sure it is the correct approach.



      collectionname = product.objects.filter(id=id).values('collection_name').distinct()
      images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
      results = []
      for img in images:
      pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
      obj = "image": img['image_url'], "items":["attr":pbi.attr, ... for pbi in pbis]
      results.append(obj)


      What are the obvious errors in my approach here, and is there a better, cleaner way to do this? In case it is relevant, the backend is postgres.



      What I would like to be able to do in the template is something like:



      % for instance in image_url %
      collection_name Collection:
      <img src=" instance ">
      Product type: instance.type
      Product Description: instance.description
      % endfor %


      Which should output something like:



      For 1.jpg:



      Beach Collection
      <img src="1.jpg">
      Product type: bed
      Product Description: nice bed
      Product type: king bed
      Product Description: nice bed
      Product type: nightstand
      Product Description: nice ns


      For 2.jpg:



      Grass Collection
      <img src="2.jpg">
      Product type: chest
      Product Description: nice chest


      For 3.jpg:



      Apple Collection
      <img src="3.jpg">
      Product type: chest
      Product Description: nice chest


      For 4.jpg:



      Fiver Collection
      <img src="4.jpg">
      Product type: chest
      Product Description: good chest









      share|improve this question














      I have data in the following form:



      collection_name | type | manufacturer | description | image_url
      ---------------------------------------------------------------------------
      beach | bed | company a | nice bed | 1.jpg
      beach | king bed | company a | nice bed | 1.jpg
      beach | nightstand | company a | nice ns | 1.jpg
      grass | chest | company a | nice chest | 2.jpg
      apple | chest | company a | nice chest | 3.jpg
      fiver | chest | company b | good chest | 4.jpg


      and models like:



      class Product(models.Model):
      collection_name = models.TextField(null='true',blank='true')
      type = models.TextField(null='true',blank='true')
      manufacturer = models.TextField(null='true',blank='true')
      description = models.TextField(null='true',blank='true')
      image_url = models.TextField(null='true',blank='true')


      What am I trying to do in my app at the moment is:



      • Link to a product by id (using the hidden pk id field),

      • Then for that id get the collection name

      • Get a list of products with that collection name

      • Get a list of distinct image_urls from the set of products with a certain collection name *

      • for each image_url in the new set, get all records that have the same image_url

      The reason I want to do this, is as you can see in the above sample data, different products sometimes reuse the same image (some images show multiple products in one image). I want to show each image only once, while being able to show all products associated with a given image (of which there could be multiple).



      I've been thinking to do something like the following based on this answer, which I think follows the logic given above, but I'm not sure it is the correct approach.



      collectionname = product.objects.filter(id=id).values('collection_name').distinct()
      images = product.objects.filter(collection_name__in=collectionname).values("image_url").distinct()
      results = []
      for img in images:
      pbis = product.objects.filter(collection_name__in=collectionname, image_url=img['image_url'])
      obj = "image": img['image_url'], "items":["attr":pbi.attr, ... for pbi in pbis]
      results.append(obj)


      What are the obvious errors in my approach here, and is there a better, cleaner way to do this? In case it is relevant, the backend is postgres.



      What I would like to be able to do in the template is something like:



      % for instance in image_url %
      collection_name Collection:
      <img src=" instance ">
      Product type: instance.type
      Product Description: instance.description
      % endfor %


      Which should output something like:



      For 1.jpg:



      Beach Collection
      <img src="1.jpg">
      Product type: bed
      Product Description: nice bed
      Product type: king bed
      Product Description: nice bed
      Product type: nightstand
      Product Description: nice ns


      For 2.jpg:



      Grass Collection
      <img src="2.jpg">
      Product type: chest
      Product Description: nice chest


      For 3.jpg:



      Apple Collection
      <img src="3.jpg">
      Product type: chest
      Product Description: nice chest


      For 4.jpg:



      Fiver Collection
      <img src="4.jpg">
      Product type: chest
      Product Description: good chest






      django






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 18:42









      Jake RankinJake Rankin

      18510




      18510






















          1 Answer
          1






          active

          oldest

          votes


















          1














          It sounds like a couple of extra models would make it easier to work with your content: Collection and Image. For your Image model, I'd recommend using Django's ImageField, which is more fully featured than just saving the URL as text. To use ImageField, you need to install Pillow, which is a current maintained fork of the Python Image Library (PIL). Do this with pip install Pillow on the command line. An ImageField has a built-in attribute url, so you can still access the URL of your image easily (see template below). Then your new models.py can be:



          # models.py
          class Image(models.Model):
          source = models.ImageField(upload_to='my_media_path')

          class Collection(models.Model):
          name = models.CharField(max_length=30)
          products = models.ManyToManyField(Product, blank=True)
          feature_image = models.ForeignKey(Image, related_name='collections', on_delete=models.SET_NULL)

          class Product(models.Model):
          ...
          image = models.ForeignKey(Image, related_name='products', on_delete=models.SET_NULL)
          # or ManyToManyField if a product has several images


          Then you can get the other products that are in the same image as your selected product:



          bucket = Product.objects.get(pk=1)
          bucket.image.products.all()
          <Product: Bucket>
          <Product: Spade>


          And for your templates - which organise content by collection mainly:



          # query
          collections = Collection.objects.all()

          # template.html
          % for collection in collections %
          <h1> collection.name </h1>
          <img src=" collection.feature_image.source.url ">
          % for product in collection.products.all %

          <p> product.name </p>
          <p> product.description </p>

          % endfor %
          % endfor %


          EDIT:



          With no time to implement the above approach, the approach you mentioned will work fine. You can change one line in the view code to keep it simpler:



          ...
          obj = "image": img['image_url'], "items": pbis


          And then when you pass the results dict to the template context:



          % for collection in results %
          collection.items.0.collection_name Collection:
          <img src=" collection.image ">
          % for item in collection.items %
          <p>Product type: item.type </p>
          <p>Product Description: item.description </p>
          % endfor %
          % endfor %





          share|improve this answer

























          • Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

            – Jake Rankin
            Mar 8 at 22:06











          • I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

            – Jake Rankin
            Mar 8 at 22:06











          • I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

            – birophilo
            Mar 8 at 22:33











          • If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

            – birophilo
            Mar 8 at 22:33












          • I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

            – Jake Rankin
            Mar 8 at 23:02











          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%2f55069183%2fdjango-performing-a-subquery-on-a-subquery-and-then-getting-all-associated-fie%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









          1














          It sounds like a couple of extra models would make it easier to work with your content: Collection and Image. For your Image model, I'd recommend using Django's ImageField, which is more fully featured than just saving the URL as text. To use ImageField, you need to install Pillow, which is a current maintained fork of the Python Image Library (PIL). Do this with pip install Pillow on the command line. An ImageField has a built-in attribute url, so you can still access the URL of your image easily (see template below). Then your new models.py can be:



          # models.py
          class Image(models.Model):
          source = models.ImageField(upload_to='my_media_path')

          class Collection(models.Model):
          name = models.CharField(max_length=30)
          products = models.ManyToManyField(Product, blank=True)
          feature_image = models.ForeignKey(Image, related_name='collections', on_delete=models.SET_NULL)

          class Product(models.Model):
          ...
          image = models.ForeignKey(Image, related_name='products', on_delete=models.SET_NULL)
          # or ManyToManyField if a product has several images


          Then you can get the other products that are in the same image as your selected product:



          bucket = Product.objects.get(pk=1)
          bucket.image.products.all()
          <Product: Bucket>
          <Product: Spade>


          And for your templates - which organise content by collection mainly:



          # query
          collections = Collection.objects.all()

          # template.html
          % for collection in collections %
          <h1> collection.name </h1>
          <img src=" collection.feature_image.source.url ">
          % for product in collection.products.all %

          <p> product.name </p>
          <p> product.description </p>

          % endfor %
          % endfor %


          EDIT:



          With no time to implement the above approach, the approach you mentioned will work fine. You can change one line in the view code to keep it simpler:



          ...
          obj = "image": img['image_url'], "items": pbis


          And then when you pass the results dict to the template context:



          % for collection in results %
          collection.items.0.collection_name Collection:
          <img src=" collection.image ">
          % for item in collection.items %
          <p>Product type: item.type </p>
          <p>Product Description: item.description </p>
          % endfor %
          % endfor %





          share|improve this answer

























          • Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

            – Jake Rankin
            Mar 8 at 22:06











          • I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

            – Jake Rankin
            Mar 8 at 22:06











          • I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

            – birophilo
            Mar 8 at 22:33











          • If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

            – birophilo
            Mar 8 at 22:33












          • I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

            – Jake Rankin
            Mar 8 at 23:02















          1














          It sounds like a couple of extra models would make it easier to work with your content: Collection and Image. For your Image model, I'd recommend using Django's ImageField, which is more fully featured than just saving the URL as text. To use ImageField, you need to install Pillow, which is a current maintained fork of the Python Image Library (PIL). Do this with pip install Pillow on the command line. An ImageField has a built-in attribute url, so you can still access the URL of your image easily (see template below). Then your new models.py can be:



          # models.py
          class Image(models.Model):
          source = models.ImageField(upload_to='my_media_path')

          class Collection(models.Model):
          name = models.CharField(max_length=30)
          products = models.ManyToManyField(Product, blank=True)
          feature_image = models.ForeignKey(Image, related_name='collections', on_delete=models.SET_NULL)

          class Product(models.Model):
          ...
          image = models.ForeignKey(Image, related_name='products', on_delete=models.SET_NULL)
          # or ManyToManyField if a product has several images


          Then you can get the other products that are in the same image as your selected product:



          bucket = Product.objects.get(pk=1)
          bucket.image.products.all()
          <Product: Bucket>
          <Product: Spade>


          And for your templates - which organise content by collection mainly:



          # query
          collections = Collection.objects.all()

          # template.html
          % for collection in collections %
          <h1> collection.name </h1>
          <img src=" collection.feature_image.source.url ">
          % for product in collection.products.all %

          <p> product.name </p>
          <p> product.description </p>

          % endfor %
          % endfor %


          EDIT:



          With no time to implement the above approach, the approach you mentioned will work fine. You can change one line in the view code to keep it simpler:



          ...
          obj = "image": img['image_url'], "items": pbis


          And then when you pass the results dict to the template context:



          % for collection in results %
          collection.items.0.collection_name Collection:
          <img src=" collection.image ">
          % for item in collection.items %
          <p>Product type: item.type </p>
          <p>Product Description: item.description </p>
          % endfor %
          % endfor %





          share|improve this answer

























          • Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

            – Jake Rankin
            Mar 8 at 22:06











          • I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

            – Jake Rankin
            Mar 8 at 22:06











          • I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

            – birophilo
            Mar 8 at 22:33











          • If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

            – birophilo
            Mar 8 at 22:33












          • I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

            – Jake Rankin
            Mar 8 at 23:02













          1












          1








          1







          It sounds like a couple of extra models would make it easier to work with your content: Collection and Image. For your Image model, I'd recommend using Django's ImageField, which is more fully featured than just saving the URL as text. To use ImageField, you need to install Pillow, which is a current maintained fork of the Python Image Library (PIL). Do this with pip install Pillow on the command line. An ImageField has a built-in attribute url, so you can still access the URL of your image easily (see template below). Then your new models.py can be:



          # models.py
          class Image(models.Model):
          source = models.ImageField(upload_to='my_media_path')

          class Collection(models.Model):
          name = models.CharField(max_length=30)
          products = models.ManyToManyField(Product, blank=True)
          feature_image = models.ForeignKey(Image, related_name='collections', on_delete=models.SET_NULL)

          class Product(models.Model):
          ...
          image = models.ForeignKey(Image, related_name='products', on_delete=models.SET_NULL)
          # or ManyToManyField if a product has several images


          Then you can get the other products that are in the same image as your selected product:



          bucket = Product.objects.get(pk=1)
          bucket.image.products.all()
          <Product: Bucket>
          <Product: Spade>


          And for your templates - which organise content by collection mainly:



          # query
          collections = Collection.objects.all()

          # template.html
          % for collection in collections %
          <h1> collection.name </h1>
          <img src=" collection.feature_image.source.url ">
          % for product in collection.products.all %

          <p> product.name </p>
          <p> product.description </p>

          % endfor %
          % endfor %


          EDIT:



          With no time to implement the above approach, the approach you mentioned will work fine. You can change one line in the view code to keep it simpler:



          ...
          obj = "image": img['image_url'], "items": pbis


          And then when you pass the results dict to the template context:



          % for collection in results %
          collection.items.0.collection_name Collection:
          <img src=" collection.image ">
          % for item in collection.items %
          <p>Product type: item.type </p>
          <p>Product Description: item.description </p>
          % endfor %
          % endfor %





          share|improve this answer















          It sounds like a couple of extra models would make it easier to work with your content: Collection and Image. For your Image model, I'd recommend using Django's ImageField, which is more fully featured than just saving the URL as text. To use ImageField, you need to install Pillow, which is a current maintained fork of the Python Image Library (PIL). Do this with pip install Pillow on the command line. An ImageField has a built-in attribute url, so you can still access the URL of your image easily (see template below). Then your new models.py can be:



          # models.py
          class Image(models.Model):
          source = models.ImageField(upload_to='my_media_path')

          class Collection(models.Model):
          name = models.CharField(max_length=30)
          products = models.ManyToManyField(Product, blank=True)
          feature_image = models.ForeignKey(Image, related_name='collections', on_delete=models.SET_NULL)

          class Product(models.Model):
          ...
          image = models.ForeignKey(Image, related_name='products', on_delete=models.SET_NULL)
          # or ManyToManyField if a product has several images


          Then you can get the other products that are in the same image as your selected product:



          bucket = Product.objects.get(pk=1)
          bucket.image.products.all()
          <Product: Bucket>
          <Product: Spade>


          And for your templates - which organise content by collection mainly:



          # query
          collections = Collection.objects.all()

          # template.html
          % for collection in collections %
          <h1> collection.name </h1>
          <img src=" collection.feature_image.source.url ">
          % for product in collection.products.all %

          <p> product.name </p>
          <p> product.description </p>

          % endfor %
          % endfor %


          EDIT:



          With no time to implement the above approach, the approach you mentioned will work fine. You can change one line in the view code to keep it simpler:



          ...
          obj = "image": img['image_url'], "items": pbis


          And then when you pass the results dict to the template context:



          % for collection in results %
          collection.items.0.collection_name Collection:
          <img src=" collection.image ">
          % for item in collection.items %
          <p>Product type: item.type </p>
          <p>Product Description: item.description </p>
          % endfor %
          % endfor %






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 23:28

























          answered Mar 8 at 21:47









          birophilobirophilo

          549615




          549615












          • Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

            – Jake Rankin
            Mar 8 at 22:06











          • I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

            – Jake Rankin
            Mar 8 at 22:06











          • I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

            – birophilo
            Mar 8 at 22:33











          • If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

            – birophilo
            Mar 8 at 22:33












          • I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

            – Jake Rankin
            Mar 8 at 23:02

















          • Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

            – Jake Rankin
            Mar 8 at 22:06











          • I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

            – Jake Rankin
            Mar 8 at 22:06











          • I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

            – birophilo
            Mar 8 at 22:33











          • If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

            – birophilo
            Mar 8 at 22:33












          • I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

            – Jake Rankin
            Mar 8 at 23:02
















          Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

          – Jake Rankin
          Mar 8 at 22:06





          Thank you for your answer, this is interesting and I am still looking it over. I should note that my situation is not typical, and while I make the models with django, I import the data directly into postgres, as it comes in bulk via an API and needs to be modified a lot before it can be used. I actually have an image_path and image_url field, with the image_path field being a FileField type and is used with easy_thumbnails package.

          – Jake Rankin
          Mar 8 at 22:06













          I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

          – Jake Rankin
          Mar 8 at 22:06





          I am worried to change the model definitions like this since I think it will make importing data as I need to harder, and everything works at the moment, except for being able to query in the way I need/want to.

          – Jake Rankin
          Mar 8 at 22:06













          I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

          – birophilo
          Mar 8 at 22:33





          I see what you mean. Your approach of creating the equivalent of a collection model and queryset in memory feels awkward to me though if your display is based around collections. How about if you left the Product model and image settings as they are, and just added a Collection model to your Django project (and Postgres)? It wouldn't affect any existing data import process. And when you import the Product data, it could get-or-create a Collection based on the product's collection name and add the product to that collection - using a signal or a custom save method, for example.

          – birophilo
          Mar 8 at 22:33













          If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

          – birophilo
          Mar 8 at 22:33






          If you'd rather not do that, there is nothing wrong with the approach you mention in your question. The view code is fine and your template snippet would need only minor adjustments to work as intended.

          – birophilo
          Mar 8 at 22:33














          I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

          – Jake Rankin
          Mar 8 at 23:02





          I agree my current method is clunky, but I've been working under pressure and with limited knowledge to get this working at all. I had plans for "Version 2" to do as you suggest, to have a collection model and create it somehow when inserting data, but it's something I need/want to learn how to do and won't be able to do before I need to have this current project ready.

          – Jake Rankin
          Mar 8 at 23:02



















          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%2f55069183%2fdjango-performing-a-subquery-on-a-subquery-and-then-getting-all-associated-fie%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

          1928 у кіно

          Захаров Федір Захарович

          Ель Греко