django-queryset

Django annotated value in template

六月ゝ 毕业季﹏ 提交于 2019-12-22 05:33:14
问题 Is it possible to access annotated values on querysets in templates? For example I have the following queryset that I'm passing to my template: context[videos] = Videos.objects.annotate(view_count=Count(views)).order_by(view_count)[:100] In my template I'm trying to get the view count like this: {% for video in videos %} {{ video.view_count }} {% endfor %} Which displays nothing. However if I use: {{ video.views.count }} It seems fine - but i believe the second option recalculates the view

Django Queryset across Models?

点点圈 提交于 2019-12-22 04:33:48
问题 I have several Models and want to return a queryset of all the Models belonging to a User, I'm wondering if its possible to return one Queryset from multiple Models? 回答1: I am assuming that you mean you would like to return a single queryset of all the objects belonging to the user from each model. Do you need a queryset or just an iterable? AFAIK, heterogeneous qs's are not possible. However, you could easily return a list, a chained iterator (itertools) or a generator to do what you want.

Django F() division - How to avoid rounding off

寵の児 提交于 2019-12-22 04:03:10
问题 I have this code: q = MyModel.objects.order_by('-value1').annotate( res=ExpressionWrapper( (F('value1') / F('value2')), output_field=FloatField()), ) for i in q: print(i.value1, i.value2, i.res) So, the output will be: 5 10 0.0 1 2 0.0 But I need 5 10 0.5 1 2 0.5 Wy F() rounded the result? How not to do this? Thanks! 回答1: The result you are expecting is really easy to achieve with a raw query and really, I mean really hard to achieve with pure django. from django.db.models import FloatField,

Good practices for a flexible search page - Django

最后都变了- 提交于 2019-12-22 01:17:40
问题 I'm just wondering if there is any example I could take from others on the topic. I have a page within Django which uses filters, in order to perform searches. At the moment I'm doing a simple check for the GET parameters and adding a .filter() to a queryset accordingly: if color: query.filter(color=color) This feels a bit like an ugly way to do, and I've been a bit stuck wondering how I could make it more dynamic. Any ideas? 回答1: Try this: ALLOWED = ('color', 'size', 'model') kwargs = dict(

Count and Max after values() method on Django query

会有一股神秘感。 提交于 2019-12-21 23:48:55
问题 I have this Django model: class Action(models.Model): id = models.AutoField(primary_key=True) game = models.ForeignKey(Game) step = models.ForeignKey(Step) from_player = models.ForeignKey(Player) to_player = models.ForeignKey(Player) type = models.ForeignKey(ActionType) timestamp = models.DateTimeField(default=timezone.now) I want to do the following: Filter on game, step and type Find the player/players how has/have obtained the highest number of actions to do so I tried: v = Action.objects

Django QuerySet querying or filtering “Odd” and/or “Even” value in a particular field

笑着哭i 提交于 2019-12-21 22:42:26
问题 # Example from django.db import models class ParkingLot(models.Model): lot_number = models.IntegerField() is_reserved = models.BooleanField() I'm interested in Odd xor Even lot_number . What's the recommended way to filter that in Django? I've posted some answer below. Challenge Does anyone know if we can use a direct comparison something like F('lot_number') % 2 == 0 technique? 回答1: In Django >1.8 you could use F() expressions: # ParkingLots with even numbered lot_numbers ParkingLot.objects

Exclude entire QuerySet from results

社会主义新天地 提交于 2019-12-21 12:43:54
问题 I have the following models: class LibraryEntry(models.Model): player = models.ForeignKey(Player) player_lib_song_id = models.IntegerField() title = models.CharField(max_length=200) artist = models.CharField(max_length=200) album = models.CharField(max_length=200) track = models.IntegerField() genre = models.CharField(max_length=50) duration = models.IntegerField() is_deleted = models.BooleanField(default=False) class Meta: unique_together = ("player", "player_lib_song_id") def __unicode__

Selecting specific fields using select_related in Django

落花浮王杯 提交于 2019-12-21 06:50:57
问题 I have two models Article and Blog related using a foreign key. I want to select only blog name while extracting the article. articles = Articles.objects.all().select_related('blog__name') The query generated shows that it selected all the fields from the Blog model. I tried using only() and defer() with select_related but both didn't work out. articles = Articles.objects.all().select_related('blog__name').only('blog__name', 'title', 'create_time') The above query resulted in error: Invalid

Django prefetch_related with m2m through relationship

三世轮回 提交于 2019-12-21 05:11:07
问题 I have the following models class Film(models.Model): crew = models.ManyToManyField('Person', through='Role', blank=True) class Role(models.Model): person = models.ForeignKey('Person') film = models.ForeignKey('Film') person_role = models.ForeignKey(RoleType) credit = models.CharField(max_length=200) credited_as = models.CharField(max_length=100) class RoleType(models.Model): """Actor, director, makeup artist...""" name = models.CharField(max_length=50) class Person(models.Model): slug =

Subclassed django models with integrated querysets

孤街浪徒 提交于 2019-12-21 04:37:09
问题 Like in this question, except I want to be able to have querysets that return a mixed body of objects: >>> Product.objects.all() [<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...] I figured out that I can't just set Product.Meta.abstract to true or otherwise just OR together querysets of differing objects. Fine, but these are all subclasses of a common class, so if I leave their superclass as non-abstract I should be happy, so long as I can get its manager to return objects