Django Pivot Table Creation - django

Good Afternoon,
I am working on a Django App. I have created a model like below.
From that model I would like to create a view displaying such a table as below:
As you can see I would like to create rows per country name in the model database and I would like to give counts per specification.
I could create the table with the country names by adding a meta class to the model for the country field and then loop it with template injection. To do that I also created a view as below:
def sum(request):
country_list_unique = Project.objects.order_by().values('country_ordering').distinct()
return render(request, 'project/project_sum.html', {'sumup':country_list_unique})
However, I don't have much of an idea how can I count the different specifications per country in views.py and how to inject them into html with Django.
I would appreciate any help.
Thank you very much in advance.

You can easily get the data using https://github.com/martsberger/django-pivot

Related

Caching list of id's of django queryset, and reusing that list for another Viewset

Let's use these 4 simple models for example. A city can have multiple shops, and a shop can have multiple products, and a product can have multiple images.
models.py
class City(models.Model):
name=models.CharField(max_length=300)
class Shop(models.Model):
name = models.CharField(max_length=300)
city = models.ForeignKey(City, related_name='related_city', on_delete=models.CASCADE)
class Product(models.Model):
name=models.CharField(max_length=300)
description=models.CharField(max_length=5000)
shop=models.ForeignKey(Shop, related_name='related_shop', on_delete=models.CASCADE)
class Image(models.Model):
image=models.ImageField(null=True)
product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE)
For an eCommerce website, users will be writing keywords and I filter on the products names, to get the matching results. I also want to fetch together the related data of shops, cities and images, relevant to the products I will be showing.
To achieve that I am using .select_related() to retrieve the other objects from the foreignKeys as well.
Now, my question is, what is the best way to send that to the client?
One way is to make a single serializer, that groups all data from all 4 tables in a single JSON. That JSON will look like 1NF, since it will have many repetitions, for example, there will be new row for every image, and every shop that the product can be found, and the 10.000 character long description will be repeated for each row, so this is not such a good idea. More specifically the fields are: (product_id, product_name, product_description, product_image_filepath, product_in_shop_id, shop_in_city_id)
The second approach will use Django queryset caching, which I have no experience at all, and maybe you can give me advice on how to make it efficient.
The second way would be to get Product.objects.filter(by input keywords).select_related().all(), cache this list of id's of products, and return this queryset of the viewset.
Then, from the client's side, I make another GET request, just for the images, and I don't know how to reuse the list of id's of products, that I queried earlier, in the previous viewset / queryset.
How do I fetch only the images that I need, for products that matched the user input keywords, such that I don't need to query the id's of products again?
How will the code look like exactly, for caching this in one viewset, and reusing it again in another viewset?
Then I also need one more GET request to get the list of shops and cities, where the product is available, so it will be fantastic if I can reuse the list of id's I got from the first queryset to fetch the products.
Is the second approach a good idea? If yes, how to implement it exactly?
Or should I stick with the first approach, which I am sceptical is the right way to do this.
I am using PostgreSQL database, and I will probably end up using ElasticSearch for my search engine, to quickly find the matching keywords.

Search Django Objects order_by(child_model_field)

I have two models in my Django application. The first one is Journey and Second is Schedule.
The Schedule models has a foreign key of Journey model. the schema of these models is as follow.
class Journey(models.Model):
pass
class Schedule(models.Model):
journey=models.ForeignKey(Journey)
day=models.CharField(max_lenth=3, choices=days)
start_time=models.TimeField()
def __unicode__(self):
return self.day
What I want to do is that when I run query Journey.objects.all() it should return the journey in order_by(Schedule.start_time). Like Journey.objects.all().order_by(Schedule.journey)
is it possible in Django ORM or does this feature provided by django or i have to make a custom query to do it.
Guidance will be appreciable
You can try like this:
Journey.objects.all().order_by('schedule__journey')
The format for querying child model field/reverse lookup is like this:
ParentModel.objects.all().order_by('lowercase_child_modelname__fieldname)')
For details, check here: https://docs.djangoproject.com/en/1.7/topics/db/queries/#lookups-that-span-relationships

How to use Dynamic fields in models?

I want to use a dynamic field in django means I have one model whose one is what be specified in the other model.
I hope i can explain it to you through example.
I have one model name product and each time a new product is uploaded we have to set some attributes for that and that attributes are specified in the 2nd table means in this product model one field is dynamic which depends on the 2nd table. if i select 'x' in other table then that field is shown here and if i select 'y' then that will be shown here,So that based on that product id and attribute id I can specify the attribute value in 3rd table so that in future i can fetch that value for a specified product.
I have tried this a lot but i do not know how to use dynamic fields in django, So can anybody let me know how i can do this.
Thanks
I recommend you to use django-json-field for that purpose ( https://github.com/derek-schaefer/django-json-field ). It uses only one Text field in your db, but you can access objects in your json like a python objects:
json = JSONField() #in your model
json = "{'attributes':{'colour':'blue','size':'2'}, 'image-height':'200px'}" # in your db
{{product.json.attributes}} #in your template
product.json.attributes #in your views
It's a great way to make many 'django' fields, while storing it only in one Text field in db.
The disadvantages of this approach is that you can't effectively search for the fields using your database, but if you have a few dozens of products, you can do the filter by python right in view.

dependent fields in django admin

I want to add, some fields depending on others. I have city and country model. I can include country as foreign key in city model. And then if I will add both city and country in another model ( say content) then will it be just like dependent selectboxes? like cities will be shown based on selected country via ajax? If not then what is correct way? and also is there a way to add city on the spot while adding main content data if city is not already on list?
So are above possible by using django admin or is it that django don't give? If not then how can it be done in django autogenerated admin?
You can do exactly what you ask using django-smart-selects
Hope that helps...
I can include country as foreign key in city model
This seems like a good idea.
And then if I will add both city and country in another model ( say content) then will it be just like dependent selectboxes? like cities will be shown based on selected country via ajax?
No, it will not get filtered automatically, you will need to write that code yourself. Both in admin and on frontend.
and also is there a way to add city on the spot while adding main content data if city is not already on list?
You will get this in the admin area.
Go ahead and start doing it, and when you run into specific problems, post them here if you can't solve it. Also read the Django docs, it is pretty elaborate on the topic of models.

Django ManyToMany in one query

I'm trying to optimise my app by keeping the number of queries to a minimum... I've noticed I'm getting a lot of extra queries when doing something like this:
class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=127, blank=False)
class Project(models.Model):
categories = models.ManyToMany(Category)
Then later, if I want to retrieve a project and all related categories, I have to do something like this :
{% for category in project.categories.all() %}
Whilst this does what I want it does so in two queries. I was wondering if there was a way of joining the M2M field so I could get the results I need with just one query? I tried this:
def category_list(self):
return self.join(list(self.category))
But it's not working.
Thanks!
Which, whilst does what I want, adds an extra query.
What do you mean by this? Do you want to pick up a Project and its categories using one query?
If you did mean this, then unfortunately there is no mechanism at present to do this without resorting to a custom SQL query. The select_related() mechanism used for foreign keys won't work here either. There is (was?) a Django ticket open for this but it has been closed as "wontfix" by the Django developers.
What you want is not seem to possible because,
In DBMS level, ManyToMany relatin is not possible, so an intermediate table is needed to join tables with ManyToMany relation.
On Django level, for your model definition, django creates an ectra table to create a ManyToMany connection, table is named using your two tables, in this example it will be something like *[app_name]_product_category*, and contains foreignkeys for your two database table.
So, you can not even acces to a field on the table with a manytomany connection via django with a such categories__name relation in your Model filter or get functions.