I have a table name "Like" and column named "value". It contains two values, either "Like" or "Unlike". How do i get the column value with only "Like" using Like.objects.values(). I have tried,
query = Like.objects.values({'value': 'Like'}).order_by().annotate(Count('value'))
It's throwing,
AttributeError: 'dict' object has no attribute 'split'
The objective is to get the no of likes in descending order. If i get it using object.values(), I can do something like below to sort,
sorted_dec = sorted(query, key=lambda x:x['value'], reverse=True)[0:5]
Or is there any better logic to approach this?
models.py:
class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextField(blank=False, null=True, validators=[MinLengthValidator(200)])
liked = models.ManyToManyField(User, default=None, blank=True, related_name = 'liked')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name = 'author')
def __str__(self):
return self.title
#property
def num_likes(self):
return self.liked.all().count()
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
LIKE_CHOICES = (
('Like', 'Like'),
('Unlike', 'Unlike'),
)
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
value = models.CharField(choices= LIKE_CHOICES,default='Like', max_length=10)
def __str__(self):
return str(self.post)
The following query will give you the queryset containing dictionaries in it.
query = Like.objects.filter(value='Like').values()
Related
I want to calculate most popular post by each category, but i have this error DISTINCT ON fields is not supported by this database backend.
after i use PostgreSql, but I also had a error. annotation and distinct together did not work.
model -->
class Category(models.Model):
title = models.CharField(max_length=150, verbose_name=_("კატეგორია"))
def __str__(self):
return self.title
class Question(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, verbose_name=_("მომხმარებელი")
)
category = models.ManyToManyField(Category)
title = models.CharField(max_length=150, verbose_name=_("სათაური"))
body = models.TextField(verbose_name=_("ტექსტი"))
image = models.ImageField(blank=True, null=True, verbose_name=_("ფოტო"))
link = models.URLField(
max_length=400,
blank=True,
null=True,
validators=[RequireHttpOrHttpsUrl()],
verbose_name=_("ლინკი"),
)
time = models.DateTimeField(auto_now=True)
send_notification = models.BooleanField(
default=True, verbose_name=_("გავაგზავნოთ შეტყობინება?")
)
def __str__(self):
return self.title
class LikeDislike(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, verbose_name=_("მომხმარებელი")
)
question = models.ForeignKey(
Question, on_delete=models.CASCADE, verbose_name=_("კითხვა")
)
point = models.BooleanField()
time = models.DateTimeField()
def __str__(self):
return self.question.title
view ->
class CountLikeByCategory(generics.ListCreateAPIView):
serializer_class = CountLikeByCategorySerializer
def get_queryset(self):
query=Question.objects.values_list(
'category__title','title'
).annotate(
l=Count('likedislike',filter=Q(likedislike__point=1)),
d=Count('likedislike',filter=Q(likedislike__point=0)),
total=F('l')+F('d'),
).order_by('category', '-total').distinct('category')
return query
who can help me?
i wan correct query
try this:
def get_queryset(self):
query=Question.objects.values_list(
'category','category__title','title'
).annotate(
l=Count('likedislike',filter=Q(likedislike__point=1)),
d=Count('likedislike',filter=Q(likedislike__point=0)),
total=F('l')+F('d'),
).order_by('category', '-total').distinct('category')
return query
I am building a Blog App and I am trying to sort or order_by in list which contains multiple queries.
models.py
class BlogPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30)
date = models.DateTimeField(auto_now_add=True)
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
blog_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
body = models.CharField(max_length=30, default='')
date_added = models.DateTimeField(auto_now_add=True)
views.py
def mypage(request):
query_1 = list(BlogPost.objects.filter(user=request.user).order_by('-date'))
query_2 = list(Comment.objects.filter(user=request.user).order_by('date_added'))
results = sorted(chain(query_1, query_2),key=attrgetter('date') , reverse=True)
context = {'results':results}
return render(reques, 'mypage.html', context)
But is showing
'Comment' object has no attribute 'date'
And I think this is because date field name is different in both model and i am sorting with only one, But i have no idea how can I sort with different field name.
Any help would be much Appreciated. Thank You
Or just add it as a property:
class Comments(models.Model): # do NOT give a model a plural name!
# ....
#property
def date(self):
return self.date_added
# or if it is a datetimefield
# return self.date_added.date()
ALso you can just write a more customized sorting key (e.g. in case the involved models are from third-party apps).
def order(obj):
try:
return obj.date
except AttributeError:
return obj.date_added
# ...
results = sorted(chain(query_1, query_2), key=order, reverse=True)
I'm trying to make it so that I can show only briefs with the slug name as the category, however it does not work.
At the minute I can only use it by showing all briefs using .objects.all() however this is not suitable for my desired use case.
Do i need a slug field in the brief section too?
Models.py
class Category(models.Model):
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=50, unique=True)
class Meta:
verbose_name_plural = 'categories'
verbose_name = 'category'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('browse')
class Brief(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
brandname = models.CharField(max_length=28)
description = models.CharField(max_length=200)
date = models.DateTimeField(auto_now=True, blank=True)
category = models.ForeignKey(Category, on_delete=CASCADE)
def get_absolute_url(self):
return reverse('homepage')
Urls.py
path('browse/categories/<slug:catslug>/', views.postsinthecategory, name = 'catslug'
views.py
def postsinthecategory(request, catslug):
categories = Category.objects.all()
brief = Brief.objects.all()
if catslug:
category = get_object_or_404(Category, slug = catslug)
brief = Brief.objects.get(category=catslug)
template = 'users/categoryposts.html'
context = {'categories': categories, 'brief': brief, 'category': category}
return render(request, template,context)
You can use __slug to filter on the related model's slug field. Use filter instead of get, because you want a queryset that can contain more than brief. I would rename brief to briefs in your view to make that clearer.
briefs = Brief.objects.filter(category__slug=catslug)
Or, since you fetched the category on the previous line, you could do:
category = get_object_or_404(Category, slug = catslug)
briefs = Brief.objects.filter(category=category)
I am working on an online-shop in django.
I have linked the order model with the cart model through ForeignKey which is further linked with products model through ForeignKey.
models.py:
class products(models.Model):
image = models.ImageField(upload_to='products/')
name = models.CharField(max_length=50)
slug = models.SlugField(blank=True, unique=True)
title = models.CharField(max_length=50)
price = models.FloatField()
def __str__(self):
return self.name
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(products, on_delete=models.CASCADE) ###
slug = models.CharField(max_length=50, default='#')
quantity = models.IntegerField(default=1)
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.name}'
def get_total(self):
total = self.item.price * self.quantity
floattotal = float("{0:.2f}".format(total))
return floattotal
class order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
slug = models.SlugField()
quantity = models.IntegerField()
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.quantity} of {self.item.item__name}'
I wanted to create object of order as:
def order_view(request, slug):
cart_qs = cart.objects.filter(user=request.user, slug=slug)
cart_item = cart_qs[0]
order.objects.create(user=request.user, item=cart_item.item.name, slug=slug, quantity=cart_item.quantity) ####
It raises error as:
Cannot assign "'The latest one'": "order.item" must be a "cart" instance.
Why this error arises and how can I resolve this?
You are trying to assign string on Order instance creation where it's expecting a Cart instance. The error raised here:
item=cart_item.item.name
It should be simply:
item=cart_item
, because your model schema expect this:
item = models.ForeignKey(cart, on_delete=models.CASCADE) ###
I am really stuck on this error and it does not make sense why it does not follow the relationship backward on Registered_Courses on the foreign key for Courses when i use course_set
views.py
def registered_coursesView(request, username):
'''Page to display the registered courses of a user.'''
registeredCourses = Registered_Courses.objects.get(owner = request.user)
courseInfo = registeredCourses.course_set.all()
context = {'registeredCourses': registeredCourses, 'courseInfo':courseInfo}
return render(request, 'safetyCourseApp/registered_courses.html', context)
models.py
class Course(models.Model):
'''Offered Course information.'''
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
name = models.CharField(max_length=200, primary_key=True)
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
start_date = models.DateField()
end_date = models.DateField()
price = models.DecimalField(max_digits=10, decimal_places=2)
capacity = models.IntegerField()
registered_ppl = models.IntegerField()
def __str__(self):
"""Return a string representation of the model."""
return self.name
class Registered_Courses(models.Model):
"""Something specific learned about a Course."""
registered_course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
"""Return a string representation of the model."""
return f'{self.owner}'
Please let me know what you guys think. I cannot think of a reason why this is not working. Thanks!
As you have specified in your models, each Registered_Courses will have a FK to Course, So each Course can have multiple Registered_Courses.
But you are trying to get multiple Course objects from a single Registered_Courses
The backward relationship is something like:
>>> course = Course.objects.first()
>>> course.registered_courses_set