S
S
Stanislav Gordienko2015-08-11 07:32:37
Django
Stanislav Gordienko, 2015-08-11 07:32:37

How to add a dynamic field to the model when searching?

Hello,
Don't know how to implement the following task. There is a search form for records with coordinates, in which the user can enter keywords, and select (optional field) the distance how far from these places (the user's current place and where the place is located). Next, we search for records by keywords, and if the user has specified a distance, then we calculate the difference between the user's coordinates and the record's coordinates. If the condition is met, I need to return the post models, and add a dynamic field that will contain the value of how far the user is from these places. And then display accordingly on the search results page.
I can’t find and understand how to implement a dynamic field that we can put in the manager and return a list of found places with a dynamic field in the model.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Fateev, 2015-08-11
@svfat

Custom template filter?

@register.filter
def distance(obj, coords):
    return obj.get_distance(coords)

In the model:
def get_distance(self, coords):
    return self.calculate_distance(self.coords, coords) 
   # ^^^^ это ужасно сложный код подсчета дистанции

In template:
{% for object in object_list %}
  {{ object|distance:coords }}
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question