django-queryset

Rewrite raw SQL as Django query

大兔子大兔子 提交于 2019-12-06 09:44:01
I am trying to write this raw SQL query, info_model = list(InfoModel.objects.raw('SELECT *, max(date), count(postid) AS freq, count(DISTINCT author) AS contributors FROM crudapp_infomodel GROUP BY topicid ORDER BY date DESC')) as a django query. The following attempt does not work as I can't get related fields for 'author' and 'post'. info_model = InfoModel.objects.values('topic') .annotate( max=Max('date'), freq=Count('postid'), contributors=Count('author', distinct=True)) .order_by('-max') With raw SQL I can use SELECT * but how can I do the equivalent with the Django query? The model is,

Django multiple queryset combine into a pagination

强颜欢笑 提交于 2019-12-06 08:46:23
问题 I have combine 2 queryset from different models into a list and used pagination to display as a single list. The problem is the objects from the list are displayed by the pagination according to the models they were created from. How could I fix the list so when a new object is created from the models. It will be displayed after the recently created object even though the recent object created was from a different models. Example would be . I have a combine queryset of user's whiteboard and

Django Inline for ManyToMany generate duplicate queries

醉酒当歌 提交于 2019-12-06 08:44:25
问题 I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have. models.py class Setting(models.Model): name = models.CharField(max_length=50, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class DisplayedGroup(models.Model): name = models.CharField(max_length=30, unique=True) position = models.PositiveSmallIntegerField(default=100) class Meta: ordering = ('priority',) def __str__(self):

How to create a conversation inbox in Django

时光怂恿深爱的人放手 提交于 2019-12-06 08:36:30
I have a Message class which has fromUser , toUser , text and createdAt fields. I want to imitate a whatsapp or iMessage or any SMS inbox, meaning I want to fetch the last message for each conversation. I tried: messages = Message.objects.order_by('createdAt').distinct('fromUser', 'toUser') But this doesn't work because of SELECT DISTINCT ON expressions must match initial ORDER BY expressions error. I don't really understand what it means, I also tried: messages = Message.objects.order_by('fromUser','toUser','createdAt').distinct('fromUser', 'toUser') and such but let me not blur the real

How to write a Django QuerySet the properly computes average of DateTimeField with grouping?

人盡茶涼 提交于 2019-12-06 08:23:51
Here is my Django model: class MyModel(models.Model): a = IntegerField() b = DateTimeField() Here is the QuerySet I execute on this model to find the count, min, max and average b s for each value of a : >>> from django.db.models import Count, Max, Min, Avg >>> MyModel.objects.extra( ... select={'avg': 'AVG(UNIX_TIMESTAMP(b))'} ... ).values('a').annotate( ... count=Count('b'), ... min=Min('b'), ... max=Max('b'), ... ) Here is the result of the QuerySet above: [ {'a': 1, 'count': 5, 'min': datetime.datetime(2015, 2, 26, 1, 8, 21, tzinfo=<UTC>), 'max': datetime.datetime(2015, 2, 26, 1, 8, 22,

Django queryset specific order by based on values of foreign key

余生长醉 提交于 2019-12-06 07:22:00
I have two models, Position and Player, for a baseball site. Positions are named pitcher, catcher, first base, second base, third base, etc. class Position(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() class Player(models.Model): name = models.CharField(max_length=300) slug = models.SlugField() position = models.ForeignKey(Position) Is there a way to make one query to return players in a specific order? For example, I'd like to do something like: Player.objects.all().order_by(position=('first base', 'second base', 'third base', 'pitcher', 'catcher',)) This

Django model inheritance - only want instances of parent class in a query

假装没事ソ 提交于 2019-12-06 05:51:19
Let's say I have 2 models, one being the parent of another. How can I query all Places that aren't restaurants in Django? Place.objects.all() would include all restaurants right? I want to exclude the children from the results. Thank you! class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField() serves_pizza = models.BooleanField() According to the documentation , you can check for the existence of the lowercase model name as an attribute: places = Place.objects.all() not

How to build complex django query as a string

流过昼夜 提交于 2019-12-06 05:00:28
I am dynamically generating a query string with multiple parameters. I am trying to include the object names ('nut', 'jam') in my string. The query has to be an "OR" query. My code is below and I get the error shown below. The solutions here , here , and here did not work for me. from viewer.models import Model1 from django.db.models import Q list1 = [ {'nut' : 'peanut', 'jam' : 'blueberry'}, {'nut' : 'almond', 'jam' : 'strawberry'} ] query_string = "" for x in list1: if len(query_string) == 0: query_string = "Q(nut='%s', jam='%s')" % (x["nut"], x["jam"]) else: query_string = "%s | Q(nut='%s',

Changes in DB data not reflecting in the Django queryset in a continuously looping script

百般思念 提交于 2019-12-06 04:48:23
I am using Django's ORM to get newly added entries from a Db and pass them to a Messaging queue. I am doing this in an infinite while loop , The PROBLEM in every loop iteration I am getting the same queryset even when I have added/deleted/edited entries when this script is running, The code goes like this : while True : sleep(10 seconds) # Below is the problem line, I get the same query-set every time in new_objects # even when I have added/deleted/edited entries while this daemon is running. new_objects = Model.objects.filter(some condition) # Process new_objects and send them to MQ . . and

Django - Filter queryset with child objects (ForeignKey)

别等时光非礼了梦想. 提交于 2019-12-06 04:07:14
I have 3 Models, and 2 of them correspond to the first one. class Parent(models.Model): name = models.CharField.... ... class Child1(models.Model): parent = models.ForeignKey(Parent) ... class Child2(models.Model): parent = models.ForeignKey(Parent) ... Now, in my view I have 2 querysets filtered of Child1 and Child2 objects. Is there a way to retrieve all the Parent objects that are in the filtered querysets? Something like... children1 = Child1.objects.filter(blah=blah) children2 = Child2.objects.filter(blah=blah) parents = Parent.objects.filter(self__in=children1 or self__in=children2) NOTE