django - search function with relational queryDoes Django scale?How to fetch the top two products for each product type?Need a minimal Django file upload exampleShow information of subclass in list_display djangodifferentiate null=True, blank=True in djangoWhat is wrong with my models.py?Create a new model which have all fields of currently existing modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform field

Why are there no file insertion syscalls

How Hebrew Vowels Work

Time at 1 g acceleration to travel 100 000 light years

Is there any possible way to get these hearts as Adult Link?

Why is it easier to balance a non-moving bike standing up than sitting down?

What does it cost to buy a tavern?

Leaving job close to major deadlines

Am I legally required to provide a (GPL licensed) source code even after a project is abandoned?

Draw a symmetric alien head

Explicit song lyrics checker

How are で and いう being used in this context?

How to modify a string without altering its text properties

Print the new site header

Implementation of the Jacobi Symbol in C

Justifying Affordable Bespoke Spaceships

reverse a call to mmap()

How can the US president give an order to a civilian?

What is the highest power supply a Raspberry pi 3 B can handle without getting damaged?

Is there any way to revive my Sim?

What mathematical theory is required for high frequency trading?

Is the author of the Shu"t HaRidvaz the same one as the one known to be the rebbe of the Ariza"l?

Are intrusions within a foreign embassy considered an act of war?

In Street Fighter, what does the M stand for in M Bison?

Why is it 出差去 and not 去出差?



django - search function with relational query


Does Django scale?How to fetch the top two products for each product type?Need a minimal Django file upload exampleShow information of subclass in list_display djangodifferentiate null=True, blank=True in djangoWhat is wrong with my models.py?Create a new model which have all fields of currently existing modelDjango-Rest-Framework - How to serialize queryset from an unrelated model as nested serializerHow to expose some specific fields of model_b based on a field of model_a?How to set dynamic initial values to django modelform field






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








1















I am attempting to create a search functionality that returns products that are associated with a vendor. In each listing that is returned I would like to have the vendor name and create a link to the vendor's page using the vendor primary key.



The relationship between both tables is created in a vendor_id as a foreign key pointing to the vendor table.



Ideally in the output I could do something like:



% for product in products %
product.title <br />
product.description <br />
<a href="% url 'vendor' vendor.id %">vendor.name</a>
% endfor %


I can get all vendors, but that seems inefficient, and I am not sure how to make the relationship between the vendor who "owns" the product in that cycle of the loop. I've seen a post on select_related but that did not work for me, and appears to be used with objects.get instead of objects.filter



Here is my search functionality defined in view.py



def search(request):
queryset_list = Products.objects.order_by('id')

if 'keywords' in request.GET:
keywords = request.GET['keywords']

if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)

context =
'products': queryset_list


return render(request, 'products/search.html', context)


models (products)



class Products(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE)


models (vendor)



class Vendors(models.Model):
uid = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)









share|improve this question
























  • can you paste your models Product and Owner?

    – Nakul Narayanan
    Mar 25 at 6:05












  • @NakulNarayanan added, I haven't given them much detail yet.

    – nghs
    Mar 25 at 6:13


















1















I am attempting to create a search functionality that returns products that are associated with a vendor. In each listing that is returned I would like to have the vendor name and create a link to the vendor's page using the vendor primary key.



The relationship between both tables is created in a vendor_id as a foreign key pointing to the vendor table.



Ideally in the output I could do something like:



% for product in products %
product.title <br />
product.description <br />
<a href="% url 'vendor' vendor.id %">vendor.name</a>
% endfor %


I can get all vendors, but that seems inefficient, and I am not sure how to make the relationship between the vendor who "owns" the product in that cycle of the loop. I've seen a post on select_related but that did not work for me, and appears to be used with objects.get instead of objects.filter



Here is my search functionality defined in view.py



def search(request):
queryset_list = Products.objects.order_by('id')

if 'keywords' in request.GET:
keywords = request.GET['keywords']

if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)

context =
'products': queryset_list


return render(request, 'products/search.html', context)


models (products)



class Products(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE)


models (vendor)



class Vendors(models.Model):
uid = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)









share|improve this question
























  • can you paste your models Product and Owner?

    – Nakul Narayanan
    Mar 25 at 6:05












  • @NakulNarayanan added, I haven't given them much detail yet.

    – nghs
    Mar 25 at 6:13














1












1








1








I am attempting to create a search functionality that returns products that are associated with a vendor. In each listing that is returned I would like to have the vendor name and create a link to the vendor's page using the vendor primary key.



The relationship between both tables is created in a vendor_id as a foreign key pointing to the vendor table.



Ideally in the output I could do something like:



% for product in products %
product.title <br />
product.description <br />
<a href="% url 'vendor' vendor.id %">vendor.name</a>
% endfor %


I can get all vendors, but that seems inefficient, and I am not sure how to make the relationship between the vendor who "owns" the product in that cycle of the loop. I've seen a post on select_related but that did not work for me, and appears to be used with objects.get instead of objects.filter



Here is my search functionality defined in view.py



def search(request):
queryset_list = Products.objects.order_by('id')

if 'keywords' in request.GET:
keywords = request.GET['keywords']

if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)

context =
'products': queryset_list


return render(request, 'products/search.html', context)


models (products)



class Products(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE)


models (vendor)



class Vendors(models.Model):
uid = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)









share|improve this question
















I am attempting to create a search functionality that returns products that are associated with a vendor. In each listing that is returned I would like to have the vendor name and create a link to the vendor's page using the vendor primary key.



The relationship between both tables is created in a vendor_id as a foreign key pointing to the vendor table.



Ideally in the output I could do something like:



% for product in products %
product.title <br />
product.description <br />
<a href="% url 'vendor' vendor.id %">vendor.name</a>
% endfor %


I can get all vendors, but that seems inefficient, and I am not sure how to make the relationship between the vendor who "owns" the product in that cycle of the loop. I've seen a post on select_related but that did not work for me, and appears to be used with objects.get instead of objects.filter



Here is my search functionality defined in view.py



def search(request):
queryset_list = Products.objects.order_by('id')

if 'keywords' in request.GET:
keywords = request.GET['keywords']

if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)

context =
'products': queryset_list


return render(request, 'products/search.html', context)


models (products)



class Products(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
vendor = models.ForeignKey(Vendors, on_delete=models.CASCADE)


models (vendor)



class Vendors(models.Model):
uid = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)






django






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 6:13







nghs

















asked Mar 25 at 5:55









nghsnghs

6011




6011












  • can you paste your models Product and Owner?

    – Nakul Narayanan
    Mar 25 at 6:05












  • @NakulNarayanan added, I haven't given them much detail yet.

    – nghs
    Mar 25 at 6:13


















  • can you paste your models Product and Owner?

    – Nakul Narayanan
    Mar 25 at 6:05












  • @NakulNarayanan added, I haven't given them much detail yet.

    – nghs
    Mar 25 at 6:13

















can you paste your models Product and Owner?

– Nakul Narayanan
Mar 25 at 6:05






can you paste your models Product and Owner?

– Nakul Narayanan
Mar 25 at 6:05














@NakulNarayanan added, I haven't given them much detail yet.

– nghs
Mar 25 at 6:13






@NakulNarayanan added, I haven't given them much detail yet.

– nghs
Mar 25 at 6:13













2 Answers
2






active

oldest

votes


















1














You could access the vender of the corresponding product by product.vendor.id in the template
try this,



% for product in products %
product.title <br />
product.description <br />
<a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
% endfor %





share|improve this answer






























    1














    you can do something like this



    % for product in products %
    product.title <br />
    product.description <br />
    <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
    % endfor %





    share|improve this answer























    • Excellent, this did work, however I don't understand how. Could you explain it?

      – nghs
      Mar 25 at 6:25






    • 1





      please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

      – Nakul Narayanan
      Mar 25 at 6:28












    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%2f55331945%2fdjango-search-function-with-relational-query%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









    1














    You could access the vender of the corresponding product by product.vendor.id in the template
    try this,



    % for product in products %
    product.title <br />
    product.description <br />
    <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
    % endfor %





    share|improve this answer



























      1














      You could access the vender of the corresponding product by product.vendor.id in the template
      try this,



      % for product in products %
      product.title <br />
      product.description <br />
      <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
      % endfor %





      share|improve this answer

























        1












        1








        1







        You could access the vender of the corresponding product by product.vendor.id in the template
        try this,



        % for product in products %
        product.title <br />
        product.description <br />
        <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
        % endfor %





        share|improve this answer













        You could access the vender of the corresponding product by product.vendor.id in the template
        try this,



        % for product in products %
        product.title <br />
        product.description <br />
        <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
        % endfor %






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 25 at 6:16









        JPGJPG

        21k31142




        21k31142























            1














            you can do something like this



            % for product in products %
            product.title <br />
            product.description <br />
            <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
            % endfor %





            share|improve this answer























            • Excellent, this did work, however I don't understand how. Could you explain it?

              – nghs
              Mar 25 at 6:25






            • 1





              please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

              – Nakul Narayanan
              Mar 25 at 6:28
















            1














            you can do something like this



            % for product in products %
            product.title <br />
            product.description <br />
            <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
            % endfor %





            share|improve this answer























            • Excellent, this did work, however I don't understand how. Could you explain it?

              – nghs
              Mar 25 at 6:25






            • 1





              please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

              – Nakul Narayanan
              Mar 25 at 6:28














            1












            1








            1







            you can do something like this



            % for product in products %
            product.title <br />
            product.description <br />
            <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
            % endfor %





            share|improve this answer













            you can do something like this



            % for product in products %
            product.title <br />
            product.description <br />
            <a href="% url 'vendor' product.vendor.id %">product.vendor.name</a>
            % endfor %






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 25 at 6:17









            Nakul NarayananNakul Narayanan

            618711




            618711












            • Excellent, this did work, however I don't understand how. Could you explain it?

              – nghs
              Mar 25 at 6:25






            • 1





              please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

              – Nakul Narayanan
              Mar 25 at 6:28


















            • Excellent, this did work, however I don't understand how. Could you explain it?

              – nghs
              Mar 25 at 6:25






            • 1





              please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

              – Nakul Narayanan
              Mar 25 at 6:28

















            Excellent, this did work, however I don't understand how. Could you explain it?

            – nghs
            Mar 25 at 6:25





            Excellent, this did work, however I don't understand how. Could you explain it?

            – nghs
            Mar 25 at 6:25




            1




            1





            please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

            – Nakul Narayanan
            Mar 25 at 6:28






            please go through this doc! docs.djangoproject.com/en/2.1/ref/models/fields/… when you try to access the field product.vendor django orm will perform a join operation with vendor table and return the instance of vendor_id

            – Nakul Narayanan
            Mar 25 at 6:28


















            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%2f55331945%2fdjango-search-function-with-relational-query%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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현