I want to list all the categories in my news table plus add the number of post in each categories.
Here is my model :
class Blog(models.Model):
titre_article = models.CharField(max_length=255)
auteur_article = models.ForeignKey(User, on_delete=models.CASCADE)
date_article = models.DateTimeField(auto_now_add=True)
modif_article = models.DateTimeField(auto_now=True)
categorie_article = models.ForeignKey('BlogCat',
on_delete=models.CASCADE,
default='1')
contenu = RichTextField(null=False)
def __str__(self):
return self.titre_article
def get_absolute_url(self):
return f"/blog/{self.id}"
class BlogCat(models.Model):
nom_categorie = models.CharField(max_length=255)
def __str__(self):
return self.nom_categorie
def get_absolute_url(self):
return f"/blog/cat/{self.nom_categorie}"
From there I can't imagine what the code in the view.py should be.
Can someone help ?
Thx a lot :)
Jeff
You can annotate your BlogCat model with the number of Blogs:
from django.db.models import Count
BlogCat.objects.annotate(nblog=Count('blog'))
The BlogCat objects that arise from this queryset will have an extra attribute .nblog that contains the number of related Blog objects.
You have to use cout()
obj = YourObject.objects.all().count()
Related
I have Post model linked with Vote model in one-to-many relationship. when i try to filter posts with most votes .filter() returns posts duplicated as many as the votes it received
i tried to understand & use .distinct() function as recommended in similar questions but it doesn't turn out to be working.
here's the Post model:
class Post(models.Model):
text = models.CharField(max_length=450)
posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
posted_at = models.DateTimeField(editable=False, default=timezone.now)
status = models.CharField(choices=status, default='PENDING', max_length=15)
def __str__(self):
return self.text
& Vote model:
class Vote(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
def __str__(self):
return f'{str(self.user)} - {str(self.post)}'
views.py:
class PostsView(TemplateView):
template_name = 'posts.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['most_voted_posts'] = Post.objects.filter(status='PUBLISHED').order_by('-vote')
return context
You need to first annotate each Post in your queryset with the number of votes by using Count, using this annotation on a vanilla/non-filtered queryset should not produce duplicates. Then you can order by this annotation:
from django.db.models import Count
Post.objects.annotate(num_votes=Count('vote')).order_by('-num_votes')
I have been playing around with Django's many to many field with the following models:
class ProjectLanguage(models.Model):
title = models.CharField(max_length=15)
def __str__(self):
return self.title
class Project(models.Model):
title = models.CharField(max_length=30)
img = models.CharField(max_length=50)
main_text = models.TextField(default="main project description ...", null=True, blank=True)
languages = models.ManyToManyField(ProjectLanguage)
def __str__(self):
return self.title
I want to get a list of projects ordered by their ProjectLanguage title. How do I achieve this with Django ?
Thanks
Mark
You can define a method like this:
class Project(models.Model):
...
def ordered_languages(self):
return self.languages.all().order_by('title')
Or you may want to use a through table with ordering.
I have this models:
class Country(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return str(self.name)
class City(models.Model):
name = models.CharField(max_length=250)
country = models.ForeignKey(Country, default=None, blank=True)
def __str__(self):
return str(self.name)
class Airport(models.Model):
name = models.CharField(max_length=250)
city = models.ForeignKey(City, default=None, blank=True)
def __str__(self):
return "{0} - {1} - {2}".format(self.city, self.city.country, self.name)
class Tour(models.Model):
title = models.CharField(max_length=200)
tour_from = models.ForeignKey(Airport)
tour_to = models.ForeignKey(Airport)
def __str__(self):
return str(self.title)
For string representation of Airport Django sends many requests to DB:
302.06 ms (591 queries including 586 similar and 586 duplicates )
Queries screenshot:
At tour/create page I have a ModelForm for creating a tour and Django sends these queries for displaying form.
forms.py:
class TourCreateForm(forms.ModelForm):
class Meta:
model = Tour
fields = ['title', 'tour_from', 'tour_to']
views.py:
class DashboardTourCreate(CreateView):
model = Tour
template_name = "dashboard/tour/create.html"
form_class = TourCreateForm
def get_context_data(self, **kwargs):
context = super(DashboardTourCreate, self).get_context_data(**kwargs)
context['page_name'] = ['tour', 'tour-index']
context['page_title'] = "Create Tour"
return context
How I can reduce queries count?
Root Cause
def __str__(self):
return "{0} - {1} - {2}".format(self.city, self.city.country, self.name)
When the tour_to and tour_from fields are rendered as <option> in the <select> widget the Airport.__str__ method is called. Because Airport.__str__ has self.city.county and both of these are ForeignKey's, the Django ORM issues a query to grab the airports city and the citys country.
And it does this for every single Airport that is an <option> which means the problem will get progressively worse the more Airport's that are added.
Solution
Leverage select_related[1]. select_related will tell the Django ORM to pull in the related fields ('city', 'county') whenever it grabs an Airport.
class TourCreateForm(forms.ModelForm):
class Meta:
model = Tour
fields = ['title', 'tour_from', 'tour_to']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['tour_from'].queryset = Airport.objects.select_related(
'city__country',
)
self.fields['tour_to'].queryset = Airport.objects.select_related(
'city__country',
)
[1] https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-related
As f-string is a string literal expressions evaluated at run time link, this might be faster that other string format but i am not fully sure. I am expecting following modification may reduce the over all time.
class Airport(models.Model):
name = models.CharField(max_length=250)
city = models.ForeignKey(City, default=None, blank=True)
def __str__(self):
return f"{self.city} - {self.city.country} - {self.name}"
I fix this issue by adding Queryset to forms.py:
class TourCreateForm(BaseForm):
airports = Airport.objects.select_related('city', 'city__country').all()
tour_from = forms.ModelChoiceField(queryset=airports)
tour_to = forms.ModelChoiceField(queryset=airports)
But I think this is not correct!
First of all, please forgive for my newbie questions. I did copy most of the code, and try to understand from Django documents.
Code as below:
models.py
class Order(models.Model):
ORDER_CHOICES = (
('import', 'IMPORT'),
('export', 'EXPORT')
)
storage = models.ForeignKey(Storage, on_delete=models.PROTECT)
order_type = models.CharField(max_length=6, choices=ORDER_CHOICES)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Item(models.Model):
def random_barcode():
return str(random.randint(10000000, 99999999))
type = models.ForeignKey(Type, on_delete=models.CASCADE)
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
item_name = models.CharField(max_length=50, help_text='Name of goods, max 50 characters')
barcode = models.CharField(max_length=8, default=random_barcode, unique=True)
production_date = models.DateField()
expired_date = models.DateField()
def __str__(self):
return self.item_type
forms.py
class ItemForm(ModelForm):
class Meta:
model = Item
exclude = ['order',]
fields = ['type', 'brand', 'item_name', 'production_date', 'expired_date']
ItemFormSet = inlineformset_factory(Order, Item, form=ItemForm, extra=1)
views.py
class CreatePO(CreateView):
model = Order
context_object_name = 'orders'
template_name = 'storages/create_po.html'
fields = ['order_type', 'storage',]
*#dun't know how to write below code....*
1st question: how to use inline formset to write the CreatePO view?
2nd question: I need my create PO template as below picture, how to add a "Quantity" field?
This kind of template need Javascript, right? Any alternative solution? I have no knowledge with javascript.
First of all, move the def random_barcode(): before def __str__(self): it looks so ugly formated code.
Then let's have a look in your pic, if you haven't proper experience with Javascript you can use Admin Views from Django, it's much more simple and supported by Django 2.1. Read more if you would like to give permission to everyone in a admin-views page https://docs.djangoproject.com/el/2.1/releases/2.1/#model-view-permission
So quantity will be just added inside Item class
quantity = models.PositiveSmallIntegerField(default=1)
Also for your form, in my opinion, you need modelform_factory, so I suggest to read this one https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#modelform-factory-function
My question is associated with making querysets on models that are interconnected across many to many fields.
context - an app that a student enters and has to rate his or her teachers. the questions the app shows the student have the following logic: each student must rate some teachers. Each teacher has different categories of questions associated with them ("intelligence", "respect", "empathy",etc.) and each of these categories has some questions associated with it.
The models are:
class Items(models.Model):
item = models.TextField()
def __str__(self):
return self.item
class Categories(models.Model):
category = models.CharField(max_length=50,null=True)
items_associated = models.ManyToManyField(Items)
def __str__(self):
return self.category
class Professors(models.Model):
professor = models.CharField(max_length=50,null=True)
categories_assigned = models.ManyToManyField(Categories)
def __str__(self):
return self.professor
class Students(models.Model):
student_logged = models.CharField(max_length=50,null=True)
professors_to_evaluate = models.ManyToManyField(Professors)
def __str__(self):
return self.student_logged
when a student enters the web has some associated teachers (model Students) these teachers in turn have some categories assigned (model Professors), these categories in turn have some questions associated (model Categories). I want to store in a dictionary these questions that are in the model Items. How can I do it?
I've tried to filter and __in but I can't get it.
Many thanks and thank you for the wisdom
I highly suggest you use the related_name attribute. I've added _x to the related names to make the query more obvious.
class Items(models.Model):
item = models.TextField()
def __str__(self):
return self.item
class Categories(models.Model):
category = models.CharField(max_length=50,null=True)
items_associated = models.ManyToManyField(Items, related_name='category_x')
def __str__(self):
return self.category
class Professors(models.Model):
professor = models.CharField(max_length=50,null=True)
categories_assigned = models.ManyToManyField(Categories, related_name='professor_x')
def __str__(self):
return self.professor
class Students(models.Model):
student_logged = models.CharField(max_length=50,null=True)
professors_to_evaluate = models.ManyToManyField(Professors, related_name='student_x')
def __str__(self):
return self.student_logged
items_for_student = Items.objects.filter(category_x__professor_x__student_x=student)
But also the naming conventions you are using for the fields are a bit quirky. I've used best practices below so you can see what that would look like.
Don't have a field with the same name as the model
Models should be singular (with rare exceptions)
ManyToMany or ForeignKey relations should share the name of the model to make querying self document.
With those rules here is what the best practice looks like.
class Item(models.Model):
name = models.TextField()
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=50,null=True)
items = models.ManyToManyField(Item, related_name='categories')
def __str__(self):
return self.name
class Professor(models.Model):
name = models.CharField(max_length=50,null=True)
categories = models.ManyToManyField(Category, related_name='professors')
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=50,null=True)
professors = models.ManyToManyField(Professor, related_names='students')
def __str__(self):
return self.name
And with that structure the query would look like:
items = Item.objects.filter(categories__professors__students=student)
Also note that the above query will be very expensive to run on a database as it would evaluate to 3 joins.