django-filter chained select - python

I'm using django-filters lib https://django-filter.readthedocs.io/en/master/index.html. I need to make chained select dropdown in my filters.
I knew how to make it with simple django-forms like here https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html.
When user pick region, i need to show cities in this region? Have someone idea or solution how to build filters like this?

Integrate django-smart-selects with how you perform the filtering.
This package allows you to quickly filter or group “chained” models by adding a custom foreign key or many to many field to your models. This will use an AJAX query to load only the applicable chained objects.
In analogy to the original question for Region -> City, the documentation's example is Continent -> Country which fits exactly to what is needed.
Once you select a continent, if you want only the countries on that continent to be available, you can use a ChainedForeignKey on the Location model:
class Location(models.Model):
continent = models.ForeignKey(Continent)
country = ChainedForeignKey(
Country,
chained_field="continent", # Location.continent
chained_model_field="continent", # Country.continent
show_all=False, # only the filtered results should be shown
auto_choose=True,
sort=True)
Related question:
How to use django-smart-select

Related

How to Add an Filter to this Excel sheet with this Criteria?

I have this Dataset
Now, In this Dataset, I want to Add a Filter where as we can see there are same or little different names for the same product, so we want to add a filter which if we chose LOSARTAN will show all the values in Product relating to that LOSARTAN, same for the other Products too. Basically, a Filter where we filter all the products which have similar names, if we choose one name in filter we will be able to see all the different names used for that Specific Product.
Thank you!

Python Classification Model

I have a df with many columns of info about Home Depot customer accounts. Some fields are accountname, industry, territory, country, state, city, services, etc...
I need to build a model using python that will allow me to put in a customer accountname and I will get an output of customer accounts similar to the one I put in.
So let’s say I put in customeraccount ‘Jon Doe’
I want to get other customer accounts similar to Jon Doe based on features like industry, country, other categorical variables etc..
How can I approach this? What kind of a model would I need to build?
You need to create some metric for "closeness" - your definition of distance.
You need a way to compare all (or all relevant to you) fields of a record with the others.
The best/easiest skeletal function I can come up with right now is
def rowDist(rowA, rowB):
return industryDistance(rowA.industry, rowB.industry) \
* industryDistanceWeight + geographicalDistance(rowA, rowB) \
* geographicalDistanceWeight
Then you just search for rows with lowest distance.

How to keep assigned attributes to a queryset object after filtering? Alternatives?

Maybe it's a stange answer, so i will explain why i'm doing this.
I have a model of Products. I have to assign each of them some stock.
So i have a function on the Products model that calculates a lot of neccesary things like stock and returns a QuerySet.
Since my db model is a little bit "complicated" i can't use annotations in this case. So i decided to execute this database query manually and then, assign each product on the querySet a stock attribute manually. Something like:
for product in queryset_products:
product.stock = some_stock_calc...
The problem comes when i want to use filters this queryset_product.
after executing something like:
queryset_products = queryset_products.filter(...)
the stock attribute gets lost
Any solution?
Since you can't use annotate(), if you can add a separate column to store stock in your Product table, you can make a the filter queries any time.
Maybe have a celery task that does all the calculations for each Product and save to new column.
Otherwise, without annotate you can't have the stock attribute in the queryset.
It can be solved differently, you can run one loop as
queryset_products = list(queryset_products.filter(...))
for product in queryset_products:
setattr(product, "stock") = some_stock_calc...
Basically, you need to fetch all the records from the database as query being lazy it will be lost since it will be re-evaluated unless results have been cached/stored.
All operations on the queryset like .filter() are symbolic until the queryset is enumerated. Then an SQL query is compiled and executed. It is not effective to calculate the stock on a big unfiltered queryset and then even to run it again filtered. You can split the filter to conditions unrelated to stock appended to the queryset and then a filter related to stock that you evaluate in the same Python loop where you calculate the stock.
result = []
for product in queryset_products.filter(**simple filters):
product.stock = some_stock_calc...
if product.stock > 0 or not required_on_stock:
result append(product)
A cache field of possible active products that could be on stock is very useful for the first simple filter.
Maybe the stock calculation is not more complicated then e.g. a stock at midnight plus a sum of stock operations since midnight. Then the current stock can be calculated by a Subquery in an annotation and filtered together. It will by compiled to one SQL with a main query with joins to your related models and a relative simple subquery for stock. (That would be another question.)

Django: create a model with fields derived from pandas dataframe

I have a pandas DataFrame from which I want to create a model whose fields are the df columns (and sets the right "Field" type for django).
Googled around but could only find bulk_create() tips, which, for my understanding, creates different Models.
My knowledge level: Django tutorial done, trying to exercise by creating this model from a big dataframe (many columns).
EDIT:
In practice, what I think I need is a way to write this part (in a model.py class):
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
run_date = models.DateTimeField('run_date')
...
in an automatic way by looking at a dataframe with 30+ columns and defining a field for each of them.
I suspect I'm probably thinking it in a wrong way, so I would like some redirection of that kind, if needed.

save a tuple to a django model

Is there a way to save a tuple to a django model?
example:
Class User(models.Model):
location = models.tupleField()
where User.location = (longitude, latitude)
Maybe you are looking for GeoDjango's PointField:
from django.contrib.gis.db import models
Class User(models.Model):
location = models.PointField(help_text="Represented as (longitude, latitude)”)
Honestly, i didn't see tupleField in django documentation. I think better approach is add two fields
longitude and latitude or create another model to store location and in User model add ForeignKey.
If you feel the need to save tuples in a single field, you should really look into relationships. That's the reason they were created.
Old answer:
This answer is assuming you're really saving locations.
If you're using PostgreSQL, you can use PostGIS. MySQL and Oracle has spacial fields built-in.
Django already supports Geo data. E.g. -
from django.contrib.gis.db import models
class ModelName(models.Model):
centroid = models.GeometryField(blank=True, null=True)
Then you can make all sorts of geo queries(e.g. find places that are within a specified area, sorted by distance etc) and your DBMS will take care of them. Plus from that single field, you can access your data like -
lat, long = [modelobject.centroid.x, modelobject.centroid.y]
# Or you can just use .x or .y directly
You can read more about them in the Geodjango documentation.
I recommend the Django-Geoposition app, and for extra, you can see the Latitude and Longitude in Google Maps.
I think this answer could help here as well.
--
As #p14z suggests, the best way to save my tuple was the ArrayField. For my example, I just wanted to save a Polygon extent, with this format:
(3.7739613717694787, 50.31527681737183, 4.726162032377, 50.49743217278623)
from django.contrib.postgres.fields import ArrayField
my_tuple_field = ArrayField(models.FloatField(), size=4, null=True)

Categories

Resources