Do a full text search by using two modelsHow to merge two dictionaries in a single expression?Limiting floats to two decimal pointsComparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?How do I concatenate two lists in Python?django - inlineformset_factory with more than one ForeignKeyProducts catalogue: filter by parametersCreate a new model which have all fields of currently existing modelHow to expose some specific fields of model_b based on a field of model_a?How to define Mode with generic ForeignKey in DjangoHow to check if Django Signal works?

Console-based BlackJack in C# - Follow-Up

Why are Japanese translated subtitles non-conversational?

What exactly is the Tension force?

Why does Hellboy file down his horns?

How would you write do the dialogues of two characters talking in a chat room?

Why do they not say "The Baby"

Confused about 誘われて (Sasowarete)

Add region constraint to Graphics

What is this old "lemon-squeezer" shaped pan

Won 50K! Now what should I do with it

Back to the nineties!

Does optical correction here give more aesthetic look to logo?

Ragged justification of captions depending on odd/even page

Can I activate an iPhone without an Apple ID?

Is `curl something | sudo bash -` a reasonably safe installation method?

Was adding milk to tea started to reduce employee tea break time?

School House Points (Python + SQLite)

Does Google Maps take into account hills/inclines for route times?

Why does the autopilot disengage even when it does not receive pilot input?

How are "soeben" and "eben" different from one another?

Why does the trade federation become so alarmed upon learning the ambassadors are Jedi Knights?

Crab Nebula short story from 1960s or '70s

Supporting developers who insist on using their pet language

What's the difference between soft PWM and PWM



Do a full text search by using two models


How to merge two dictionaries in a single expression?Limiting floats to two decimal pointsComparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?How do I concatenate two lists in Python?django - inlineformset_factory with more than one ForeignKeyProducts catalogue: filter by parametersCreate a new model which have all fields of currently existing modelHow to expose some specific fields of model_b based on a field of model_a?How to define Mode with generic ForeignKey in DjangoHow to check if Django Signal works?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have two models Item and Owner:



class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(
Owner, related_name='owner_items',
on_delete=models.CASCADE,
)
is_featured = models.BooleanField(
choices=CHOICES, default=BOOL_NO
)
# ...


I do a full-text search (based on Django docs) in the Item name and description fields. PostgreSQL version is 10.



search_vectors = (
SearchVector('name', weight='A', config='english') +
SearchVector('description', weight='B', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
rank=search_rank
).filter(rank__gte=0.2).order_by('-rank')


I want to introduce also the Owner, name field in the equation, also give a little boost to the rank if is_featured is true.



I have the Owner instance model before doing this search.










share|improve this question
























  • if my answer solved your question accept it!

    – Paolo Melchiorre
    Apr 18 at 7:27

















1















I have two models Item and Owner:



class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(
Owner, related_name='owner_items',
on_delete=models.CASCADE,
)
is_featured = models.BooleanField(
choices=CHOICES, default=BOOL_NO
)
# ...


I do a full-text search (based on Django docs) in the Item name and description fields. PostgreSQL version is 10.



search_vectors = (
SearchVector('name', weight='A', config='english') +
SearchVector('description', weight='B', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
rank=search_rank
).filter(rank__gte=0.2).order_by('-rank')


I want to introduce also the Owner, name field in the equation, also give a little boost to the rank if is_featured is true.



I have the Owner instance model before doing this search.










share|improve this question
























  • if my answer solved your question accept it!

    – Paolo Melchiorre
    Apr 18 at 7:27













1












1








1


1






I have two models Item and Owner:



class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(
Owner, related_name='owner_items',
on_delete=models.CASCADE,
)
is_featured = models.BooleanField(
choices=CHOICES, default=BOOL_NO
)
# ...


I do a full-text search (based on Django docs) in the Item name and description fields. PostgreSQL version is 10.



search_vectors = (
SearchVector('name', weight='A', config='english') +
SearchVector('description', weight='B', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
rank=search_rank
).filter(rank__gte=0.2).order_by('-rank')


I want to introduce also the Owner, name field in the equation, also give a little boost to the rank if is_featured is true.



I have the Owner instance model before doing this search.










share|improve this question
















I have two models Item and Owner:



class Item(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(
Owner, related_name='owner_items',
on_delete=models.CASCADE,
)
is_featured = models.BooleanField(
choices=CHOICES, default=BOOL_NO
)
# ...


I do a full-text search (based on Django docs) in the Item name and description fields. PostgreSQL version is 10.



search_vectors = (
SearchVector('name', weight='A', config='english') +
SearchVector('description', weight='B', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
rank=search_rank
).filter(rank__gte=0.2).order_by('-rank')


I want to introduce also the Owner, name field in the equation, also give a little boost to the rank if is_featured is true.



I have the Owner instance model before doing this search.







python django postgresql full-text-search django-queryset






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 10:25









Paolo Melchiorre

2,2011 gold badge21 silver badges31 bronze badges




2,2011 gold badge21 silver badges31 bronze badges










asked Mar 26 at 6:29









user3541631user3541631

1,2453 gold badges18 silver badges37 bronze badges




1,2453 gold badges18 silver badges37 bronze badges












  • if my answer solved your question accept it!

    – Paolo Melchiorre
    Apr 18 at 7:27

















  • if my answer solved your question accept it!

    – Paolo Melchiorre
    Apr 18 at 7:27
















if my answer solved your question accept it!

– Paolo Melchiorre
Apr 18 at 7:27





if my answer solved your question accept it!

– Paolo Melchiorre
Apr 18 at 7:27












1 Answer
1






active

oldest

votes


















1














You can add the field name from class Owner in the search_vector, maybe with a different weight and the same config (it's only an hypothesis because you didn't specified the Owner model definition or data).



A way to use is_featured as a boost for your rank can be annotate a 1 (you can use other values) if it's True and then add it to the SearchRank result.



from django.db import models
from django.db.models import Case, Value, When
from django.contrib.postgres.search import (
SearchQuery, SearchRank, SearchVector,
)

search_vectors = (
SearchVector('name', weight='A', config='english') +
SearchVector('description', weight='B', config='english') +
SearchVector('owner__name', weight='C', config='english')
)
terms = [SearchQuery(term) for term in keyword.split()]
search_query = functools.reduce(operator.or_, terms)
search_rank = SearchRank(
search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
)
qs = Item.objects.all().annotate(
featured_boost=Case(
When(is_featured=True, then=Value(1)),
default=Value(0),
output_field=models.IntegerField(),
)
).annotate(
rank=search_rank + featured_boost
).filter(rank__gte=0.2).order_by('-rank')





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55351016%2fdo-a-full-text-search-by-using-two-models%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














    You can add the field name from class Owner in the search_vector, maybe with a different weight and the same config (it's only an hypothesis because you didn't specified the Owner model definition or data).



    A way to use is_featured as a boost for your rank can be annotate a 1 (you can use other values) if it's True and then add it to the SearchRank result.



    from django.db import models
    from django.db.models import Case, Value, When
    from django.contrib.postgres.search import (
    SearchQuery, SearchRank, SearchVector,
    )

    search_vectors = (
    SearchVector('name', weight='A', config='english') +
    SearchVector('description', weight='B', config='english') +
    SearchVector('owner__name', weight='C', config='english')
    )
    terms = [SearchQuery(term) for term in keyword.split()]
    search_query = functools.reduce(operator.or_, terms)
    search_rank = SearchRank(
    search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
    )
    qs = Item.objects.all().annotate(
    featured_boost=Case(
    When(is_featured=True, then=Value(1)),
    default=Value(0),
    output_field=models.IntegerField(),
    )
    ).annotate(
    rank=search_rank + featured_boost
    ).filter(rank__gte=0.2).order_by('-rank')





    share|improve this answer



























      1














      You can add the field name from class Owner in the search_vector, maybe with a different weight and the same config (it's only an hypothesis because you didn't specified the Owner model definition or data).



      A way to use is_featured as a boost for your rank can be annotate a 1 (you can use other values) if it's True and then add it to the SearchRank result.



      from django.db import models
      from django.db.models import Case, Value, When
      from django.contrib.postgres.search import (
      SearchQuery, SearchRank, SearchVector,
      )

      search_vectors = (
      SearchVector('name', weight='A', config='english') +
      SearchVector('description', weight='B', config='english') +
      SearchVector('owner__name', weight='C', config='english')
      )
      terms = [SearchQuery(term) for term in keyword.split()]
      search_query = functools.reduce(operator.or_, terms)
      search_rank = SearchRank(
      search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
      )
      qs = Item.objects.all().annotate(
      featured_boost=Case(
      When(is_featured=True, then=Value(1)),
      default=Value(0),
      output_field=models.IntegerField(),
      )
      ).annotate(
      rank=search_rank + featured_boost
      ).filter(rank__gte=0.2).order_by('-rank')





      share|improve this answer

























        1












        1








        1







        You can add the field name from class Owner in the search_vector, maybe with a different weight and the same config (it's only an hypothesis because you didn't specified the Owner model definition or data).



        A way to use is_featured as a boost for your rank can be annotate a 1 (you can use other values) if it's True and then add it to the SearchRank result.



        from django.db import models
        from django.db.models import Case, Value, When
        from django.contrib.postgres.search import (
        SearchQuery, SearchRank, SearchVector,
        )

        search_vectors = (
        SearchVector('name', weight='A', config='english') +
        SearchVector('description', weight='B', config='english') +
        SearchVector('owner__name', weight='C', config='english')
        )
        terms = [SearchQuery(term) for term in keyword.split()]
        search_query = functools.reduce(operator.or_, terms)
        search_rank = SearchRank(
        search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
        )
        qs = Item.objects.all().annotate(
        featured_boost=Case(
        When(is_featured=True, then=Value(1)),
        default=Value(0),
        output_field=models.IntegerField(),
        )
        ).annotate(
        rank=search_rank + featured_boost
        ).filter(rank__gte=0.2).order_by('-rank')





        share|improve this answer













        You can add the field name from class Owner in the search_vector, maybe with a different weight and the same config (it's only an hypothesis because you didn't specified the Owner model definition or data).



        A way to use is_featured as a boost for your rank can be annotate a 1 (you can use other values) if it's True and then add it to the SearchRank result.



        from django.db import models
        from django.db.models import Case, Value, When
        from django.contrib.postgres.search import (
        SearchQuery, SearchRank, SearchVector,
        )

        search_vectors = (
        SearchVector('name', weight='A', config='english') +
        SearchVector('description', weight='B', config='english') +
        SearchVector('owner__name', weight='C', config='english')
        )
        terms = [SearchQuery(term) for term in keyword.split()]
        search_query = functools.reduce(operator.or_, terms)
        search_rank = SearchRank(
        search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]
        )
        qs = Item.objects.all().annotate(
        featured_boost=Case(
        When(is_featured=True, then=Value(1)),
        default=Value(0),
        output_field=models.IntegerField(),
        )
        ).annotate(
        rank=search_rank + featured_boost
        ).filter(rank__gte=0.2).order_by('-rank')






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 9:14









        Paolo MelchiorrePaolo Melchiorre

        2,2011 gold badge21 silver badges31 bronze badges




        2,2011 gold badge21 silver badges31 bronze badges
















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55351016%2fdo-a-full-text-search-by-using-two-models%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            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

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해