django-orm

Creating Partial Indexes with Django 1.7

五迷三道 提交于 2019-11-27 22:56:43
The documentation for Django 1.7 mentions RunSQL classes can be used to create partial indexes on your tables. I have a table where I want the combination of title , blog & category to be unique. However if category is not provided, the combination of title & blog should still be unique. class Post(models.Model): title = models.CharField(max_length=200) blog = models.ForeignKey(Blog) category = models.ForeignKey(Category, null=True, blank=True) I can achieve this constraint with partial indexes (like the SQL shown below). Where do I add this code if I'm using Django 1.7 migrations? CREATE

Annotate with value of latest related in Django 1.8 using conditional annotation

Deadly 提交于 2019-11-27 21:53:54
I have the following models: class City(models.Model): ... class Census(models.Model): city = models.ForeignKey(City) date = models.DateTimeField() value = models.BigIntegerField() Now I'd like to annotate a City-queryset with the value of the latest Census. How do I achieve that? I have tried: City.objects.annotate(population=Max('census__date')) # --> annotates date and not value City.objects.annotate(population=Max('census__value')) # --> annotates highest value, not latest City.objects.annotate(population= Case( When( census__date=Max('census__date'), then='census__value') ) ) # -->

What is the default order of a list returned from a Django filter call?

自古美人都是妖i 提交于 2019-11-27 21:47:11
Short Question What is the default order of a list returned from a Django filter call when connected to a PostgreSQL database? Background By my own admission, I had made a poor assumption at the application layer in that the order in which a list is returned will be constant, that is without using 'order_by'. The list of items I was querying is not in alphabetic order or any other deliberate order. It was thought to remain in the same order as which they were added to the database. This assumption held true for hundreds of queries, but a failure was reported by my application when the order

How to execute a GROUP BY … COUNT or SUM in Django ORM?

可紊 提交于 2019-11-27 21:43:02
Prologue: This is a question arising often in SO: Django Models Group By Django equivalent for count and group by How to query as GROUP BY in django? How to use the ORM for the equivalent of a SQL count, group and join query? I have composed an example on SO Documentation but since the Documentation will get shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post. Of course, I would be more than happy to see any different approach as well!! Question: Assume the model: class Books(models.Model):

Django: Order_by multiple fields

眉间皱痕 提交于 2019-11-27 21:10:32
问题 I am getting order_by fields in the form of a list. I want to order_by by multiple fields with django orm. List is like below: orderbyList = ['check-in','check-out','location'] I am writing a query is like: modelclassinstance.objects.all().order_by(*orderbyList) Everything i am expecting in a list is dynamic. I don't have predifined set of data.Could some tell me how to write a django ORM with this? 回答1: Try something like this modelclassinstance.objects.order_by('check-in', 'check-out',

Django queryset get exact manytomany lookup [duplicate]

自作多情 提交于 2019-11-27 20:12:10
This question already has an answer here: How to do many-to-many Django query to find book with 2 given authors? 4 answers I have a pk list of instances of Tag model, say pk_list = [10, 6, 3] I have another model with m2m field of tags and an instance that contains exactly 3 tags (of above pks). class Node(models.Model): ... tags = models.ManyToManyField(Tag, related_name='nodes') I'd like to retrieve a Node that contains exact set of tags as specified in my pk_list. When I do Node.objects.filter(tags__in=pk_list) it returns a list of three same instances [<Node: My node title>, <Node: My node

How to use custom manager with related objects?

我的梦境 提交于 2019-11-27 19:37:25
I have a custom manager. I want to use it for related objects. I found use_for_related_fields in docs. But it does not work the way I used it: class RandomQueryset(models.query.QuerySet): def randomize(self): count = self.count() random_index = random.randint(0, count - 1) return self.all()[random_index] class RandomManager(models.Manager): use_for_related_fields = True def get_query_set(self): return RandomQueryset(self.model, using=self._db) def randomize(self): return self.get_query_set().randomize() I used it for one model: >>> post = PostPages.default_manager.filter(image_gallery__isnull

In Django filter statement what's the difference between __exact and equal sign (=)?

自闭症网瘾萝莉.ら 提交于 2019-11-27 17:16:57
问题 In Django filter statement what's the difference if I write: .filter(name__exact='Alex') and .filter(name='Alex') Thanks 回答1: There is no difference, the second one implies using the __exact. From the documentation: For example, the following two statements are equivalent: >>> Blog.objects.get(id__exact=14) # Explicit form >>> Blog.objects.get(id=14) # __exact is implied This is for convenience, because exact # lookups are the common case. 回答2: You can look at the SQL that Django will execute

--fake-initial vs --fake in Django migration?

萝らか妹 提交于 2019-11-27 15:40:51
问题 What is the difference between --fake-initial and --fake in Django migrations? What are the dangers of using fake migrations? Anybody knows? Thank you very much to all. I am using django 1.10 回答1: Well the documentation is very clear about this --fake-initial Allows Django to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. This option is intended for use when first running migrations

Django ORM: Group by and Max

吃可爱长大的小学妹 提交于 2019-11-27 14:44:46
问题 I have a model that looks like this: Requests: user, req_time, req_text In the DB, the records can look like this: id, user_id, req_time, req_text 1 1 TIMESTAMP YES 2 1 TIMESTAMP NO 3 2 TIMESTAMP YES etc. How do I write a Django ORM query that: groups the Requests by user, filters the Requests based on req_text, and also, select the max id of the resulting result set. So for each user, I will return one row which matches the filter condition and also has the greatest id. 回答1: from django.db