django-orm

how to get list of objects involving many to many relation in django

浪子不回头ぞ 提交于 2019-12-05 16:44:33
问题 I have the following models: class Committee(models.Model): customer = models.ForeignKey(Customer, related_name="committees") name = models.CharField(max_length=255) members = models.ManyToManyField(member, through=CommitteeMember, related_name="committees") items = models.ManyToManyField(Item, related_name="committees", blank=True) class CommitteeRole(models.Model): committee = models.ForeignKey('Committee') member = models.ForeignKey(member) #user is the members user/user number user =

Django, queryset filter ManyToManyField

爷,独闯天下 提交于 2019-12-05 13:41:39
I do have the two models below. So I'm trying to get all the modules of a particular course. As you can see, I'm already getting that particular course. So I just need to get the modules from it. I read the docs about filtering a ManyToManyField but still couldn't make it work. I know that maybe it's too simple but can't solve it. models.py class Course(models.Model): name = models.CharField(max_length=100) modules = models.ManyToManyField('Module', blank=True) class Module(models.Model): code = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=65) year = models

Can we do a Sum on CharField in Django ORM?

孤街浪徒 提交于 2019-12-05 13:33:03
My model in Django ORM is this class Test(Modelbase): id = models.IntegerField(null=True, blank=True) amount = models.CharField(max_length=255) I want to add the amount for list of id's. The only problem is the amount field is CharField . How do I apply sum for the amount field? Test.objects.filter(id__in=[1,2,3]).aggregate(Sum('amount')) I am using Django=1.9.1 for this. you can try do annotate with cast : from django.db.models import FloatField from django.db.models.functions import Cast Test.objects.filter(id__in=[1,2,3] ).annotate(as_float=Cast('amount', FloatField()) ).aggregate(Sum('as

Django orm group by multiple columns

泪湿孤枕 提交于 2019-12-05 12:41:44
How to perform a multiple column group by in Django? I have only seen examples on one column group by. Below is the query i am trying to convert to Django ORM. SELECT order_id,city,locality,login_time,sum(morning_hours),sum(afternoon_hours),sum(evening_hours),sum(total_hours) FROM orders GROUPBY order_id,city,locality,login_time` Shubhanshu from django.db.models import Sum Your_Model.objects.values('order_id', 'city', 'locality', 'login_time').order_by().annotate(sum('morning_hours'), sum('afternoon_hours'), sum('evening_hours'), sum('total_hours')) I hope the above code snippet helps (While

Django exclude from annotation count

不打扰是莪最后的温柔 提交于 2019-12-05 07:45:52
I have following application: from django.db import models class Worker(models.Model): name = models.CharField(max_length=60) def __str__(self): return self.name class Job(models.Model): worker = models.ForeignKey(Worker) is_completed = models.BooleanField() I want to annotate Workers query with count of completed jobs. I'll try to do it with following script: from myapp.models import Worker, Job from django.db.models import Count w = Worker.objects.create(name='Worker1') Job.objects.create(worker=w, is_completed=False) Job.objects.create(worker=w, is_completed=False) Job.objects.create(worker

django's .extra(where= clauses are clobbered by table-renaming .filter(foo__in=… subselects

六月ゝ 毕业季﹏ 提交于 2019-12-05 02:19:24
问题 The short of it is, the table names of all queries that are inside a filter get renamed to u0, u1, ..., so my extra where clauses won't know what table to point to. I would love to not have to hand-make all the queries for every way I might subselect on this data, and my current workaround is to turn my extra'd queries into pk values_lists, but those are really slow and something of an abomination. Here's what this all looks like. You can mostly ignore the details of what goes in the extra of

Django query expression for calculated fields that require conditions and casting

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 01:56:07
I am trying to run an aggregation query that is roughly equals to: select sum(impressions) as impressions, sum(clicks) as clicks, sum(clicks)/sum(impressions) as ctr from stats group by product order by ctr; The database used is PostgreSQL. I made this query expression (Django 1.9): Stats.objects.values('product').annotate( impressions = models.Sum('impressions'), clicks = models.Sum('clicks'), ctr = models.ExpressionWrapper( models.F('clicks')/models.F('impressions')), output_field = models.FloatField() ) ).order_by('ctr') There are 2 problems with it: ctr is 0.0 because it divides integers

ManyToMany field not saved when using Django admin

泪湿孤枕 提交于 2019-12-05 01:05:36
I'm experiencing a weird problem which I hope someone in here may be able to shed some light on. I'm overriding the save() method of a model to add some values to a ManyToMany-field after running super(). My problem is that when I'm saving in Django admin the values seems to get added to the relationship but is then empty again. If however I do it from manage.py shell it works without problem. I've put two print statements in there and they produce the exact same output regardless of if I'm running it via Django admin or via shell. class Store(models.Model): holidays = models.ManyToManyField

Always True Q object

别来无恙 提交于 2019-12-05 00:45:23
I want to create some part of Django ORM filter query dinamicly, now I can do: if some: Obj.filter( some_f1=some_v1, f1=v1, f2=v2, f3=v3, f4=v4, ... ) else: Obj.filter( f1=v1, f2=v2, f3=v3, f4=v4, ... ) I want something without code duplicate like this: Obj.filter( Q(some_f1=some_v1) if some else True, # what to use instead of True? f1=v1, f2=v2, f3=v3, f4=v4, ... ) Here's a hacky way to get an always true Q object: always_true = ~Q(pk=None) This depends on the fact that the primary key cannot be null. Try this; conditions = {'f1':f1,'f2':f2, 'f3':f3} if some: conditions['some_f1'] = some_v1

How to select_related on reverse foreign key? [duplicate]

余生颓废 提交于 2019-12-05 00:24:59
Possible Duplicate: A left outer reverse select_related in Django? A BlogPost has many Comment s. I want to get a list of BlogPost s and all their comments. Thus, I have BlogPost.objects.filter(my_filter).select_related() But the ForeignKey is on the Comment , not the BlogPost , so the select_related() doesn't prefetch any comments. Is there a way to get this to work? I can't reverse the query ( Comment.objects... ) because then the other objects that the select_related() does fetch wouldn't work. I need it to work both ways. Why won't you fetch the comments and then use regroup template tag