django-orm

Django queryset get distinct column values with respect to other column

拜拜、爱过 提交于 2019-12-11 06:55:22
问题 I am using django orm and I am trying to get all the values of a column, but only if a different column is unique with respect to it. Its hard to explain, so here is an example: q | a | 1 w | s | 2 e | a | 3 q | a | 4 w | s | 5 e | a | 6 I would like to get all the values that are in column 2 but if they also have the same value in column 1 don't take duplicates. So in this case I want to get [a,s,a]. (column 3 only serves to show why these duplicates don't get merged in the first place).

Django - Select nested collection Avg with group by in one to many relationship

喜你入骨 提交于 2019-12-11 05:31:17
问题 I have the following models, and what I would like is to select a collection of businesses, each of them with a collection of AVG(rate) based on group by review_question_id. Here are the necessary models: class ReviewQuestion(models.Model): """Represents a question to be given in a business type """ business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) question_text = models.CharField(max_length=100) class Business(models.Model): """Values for a specific business, based on

Join two queries in Django ORM

北慕城南 提交于 2019-12-11 04:18:36
问题 I have a Person model which has a birthday. I would like to create a query that returns all the persons information along with an additional field that tells how many people are sharing each person's birthday. In SQL I would write it like this: SELECT p.name, b.count FROM persons as p INNER JOIN (SELECT birthday as date, COUNT(*) AS count FROM persons GROUP_BY birthday) AS b WHERE p.birthday = b.date With Django querysets I can do the inner select but I don't know how to do the inner join.

Django 1.8 conditional annotation results in INNER JOIN instead of LEFT OUTER JOIN

那年仲夏 提交于 2019-12-11 04:05:11
问题 The models: class Bar(GenericModel): ... class Foo(GenericModel): bar = models.ForeignKey(Bar, related_name='foo_bar') The query: bars = Bar.objects .prefetch_related('foo_bar') .annotate(sum_foo=Sum( Case( When(foo_bar__is_deleted=False, then='foo_bar__amount'), default=Value(0), output_field=IntegerField() ) ) ) The former results in an inner join: SELECT ... FROM "bar" INNER JOIN "foo" ON ( "bar"."id" = "foo"."bar_id" ) ... What I intend to obtain is a LEFT OUTER JOIN (a full list of "bar"

Django - aggregation with get_FOO_display

◇◆丶佛笑我妖孽 提交于 2019-12-11 03:14:54
问题 Consider the following: status = queryset.values('status').annotate(count=Count('status')) where status field is a CharField with choices . This will result in a list of dictionaries with status DB value along with its count. Is there a way to aggregate status and show its display value instead? I have looked up the code of _get_FIELD_display which I probably can emulate, but it feels a tad hackish to repeat the framework's internal code. 回答1: Without hacking a SQL, you may not achieve this

Choices defined for model fields not being enforced?

不问归期 提交于 2019-12-11 03:02:30
问题 So I've defined some fields as choices: class MyModel(models.Model): # Text language. ENGLISH = 'eng' FRENCH = 'fr' LANGUAGES_CHOICES = [ (ENGLISH, 'English'), (FRENCH, 'French'), ] language = models.CharField( max_length=max(len(language) for language in LANGUAGES_CHOICES), choices=LANGUAGES_CHOICES, blank=False, null=True) However, I can do MyModel(language='hurhurhur').save() without any error or complaint. What am I missing? 回答1: Django validates a model when you validate a modelform, or

Django: Does chaining filter() functions result in the same SQL as using multiple kwargs?

大城市里の小女人 提交于 2019-12-11 02:27:52
问题 In Django, do the following two snippets produce the same underlying SQL query? qs = MyModel.objects.filter(group=1, type=2) and qs = MyModel.objects.filter(group=1).filter(type=2) 回答1: It depends actually, on whether there are joins or spanned lookups, especially through M2M relationship. For example >>> print User.objects.filter(groups__gt=1).filter(groups__lt=2).query SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email",

Django ORM - .update(…) with an extra(…) and F(…)

守給你的承諾、 提交于 2019-12-11 02:13:08
问题 I want to do one sql query to update a lot of models in a Django site. I want to change one char column/field to be based on the id and some text, in MySQL (which this site is), I'd do that with "UPDATE table SET blah = 'prefix'||id||'suffix'" . My first attempt of doing this in Django was: Model.objects.update(blah='prefix'+F('id')+'suffix') But that tries to give MySQL a + , not a || operator. My next attempt was to use the .extra(…) like so: Model.objects.extra(select={'newvalue':'"prefix"

django - Get a set of objects from different models field names

寵の児 提交于 2019-12-11 01:29:51
问题 Please have a look at my models. class BackgroundImage(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to=get_upload_file_name) caption = models.CharField(max_length=200) pub_date = models.DateTimeField(default=datetime.now) class ProfilePicture(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to=get_upload_file_name) caption = models.CharField(max_length=200) pub_date = models.DateTimeField(default=datetime.now) class Album(models

Django - Populate model instance related field from cached query

泪湿孤枕 提交于 2019-12-11 00:45:45
问题 Same situation as Django prefetch_related children of children but different question: I have a model Node that looks something like that: class Node(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, null=True) A Node can have several children, and each of these children can have its own children. I would like to do something like that: def cache_children(node): for child in node.children.all(): cache_children(child) root_node = Node.objects