django-queryset

Django F() division - How to avoid rounding off

烂漫一生 提交于 2019-12-05 03:34:18
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! 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, ExpressionWrapper, F template = '%(function)s(%(expressions)s AS FLOAT)' fv1 = Func(F('value1'), function=

Django Queryset across Models?

这一生的挚爱 提交于 2019-12-05 03:09:42
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? 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. This assumes that the models referencing the user are known ahead of time. Assuming default related_name,

Django REST Framework Serialize extremely slow

放肆的年华 提交于 2019-12-05 03:09:11
I am in Python 2.7 and Django 1.7.1 with django-restframework I have an API that returns me some specific values taken fron the Database, it uses a Custom Serializer like this: class InventarioSerializer(serializers.ModelSerializer): item = serializers.RelatedField(source='producto.item') ubicacion = serializers.RelatedField(source='ubicacion.nombre') class Meta: model = Inventario fields = ('epc','item','cantidad','ubicacion') My API's view is called this way: class ItemEnInventarioViewSet(InventarioListModelMixin, viewsets.ModelViewSet): serializer_class = InventarioSerializer renderer

Django query with order_by, distinct and limit on Postgresql

微笑、不失礼 提交于 2019-12-05 03:05:23
I have the following : class Product(models.Model): name = models.CharField(max_length=255) class Action(models.Model): product = models.ForeignKey(Product) created_at = models.DateTimeField(auto_now_add=True) I would like to retrieve the 10 most recent actions ordered by created_at DESC with distinct products. The following is close to the result but still misses the ordering: Action.objects.all().order_by('product_id').distinct('product_id')[:10] Your solution seems like it's trying to do too much. It will also result in 2 separate SQL queries. This would work fine and with only a single

How to modify a queryset and save it as new objects?

强颜欢笑 提交于 2019-12-05 02:48:32
问题 I need to query for a set of objects for a particular Model, change a single attribute/column ("account"), and then save the entire queryset's objects as new objects/rows. In other words, I want to duplicate the objects, with a single attribute ("account") changed on the duplicates. I'm basically creating a new account and then going through each model and copying a previous account's objects to the new account, so I'll be doing this repeatedly, with different models, probably using django

Django Inner Join Queryset

China☆狼群 提交于 2019-12-04 23:28:11
I'm working with Django and I need to do a queryset using two inner joins. I have three models A, B, and C and I want to do a query like the following in psql: select DISTINCT a from A inner join B on B.a_id = A.id inner join C on C.b_id = B.id; Models: (only included relevant fields) class A(models.Model): id = models.IntegerField(primary_key=True) class B(models.Model): id = models.IntegerField(primary_key=True) a = models.ForeignKey(A, null=True, blank=True,on_delete=models.SET_NULL) class C(models.Model): b = models.ForeignKey(B, null=True, on_delete=models.SET_NULL) So everything in C

comparing querysets in django TestCase

若如初见. 提交于 2019-12-04 22:43:42
I have a very simple view as follows def simple_view(request): documents = request.user.document_set.all() return render(request, 'simple.html', {'documents': documents}) To test the above view in my test case i have the following method which errors out. Class SomeTestCase(TestCase): # ... def test_simple_view(self): # ... some other checks docset = self.resonse.context['documents'] self.assertTrue(self.user.document_set.all() == docset) # This line raises an error # ... The error i get is AssertionError: False is not true . I have tried printing both the querysets and both are absolutely

Django: how to aggregate / annotate over a many-to-many relationship?

瘦欲@ 提交于 2019-12-04 21:29:50
问题 I have a Person model and a Tag model, with a m2m between them. I need to extract the tag which is connected to the most records within a given Person queryset, together with the count. Is there an elegant, efficient way to extract this using the Django ORM? Better yet, is there a way to get the entire tag distribution through some annotation? How can one even pull all of the objects connected to a subset of objects connected via a m2m? Thanks! 回答1: This would give you the most frequent tag:

Good practices for a flexible search page - Django

为君一笑 提交于 2019-12-04 21:25:29
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? Try this: ALLOWED = ('color', 'size', 'model') kwargs = dict( (key, value) for key, value in request.GET.items() if key in ALLOWED ) query.filter(**kwargs) This will

Perform a logical exclusive OR on a Django Q object

…衆ロ難τιáo~ 提交于 2019-12-04 21:24:27
问题 I would like to perform a logical exclusive OR (XOR) on django.db.models.Q objects, using operator module to limit the choices of a model field to a subset of foreignkey. I am doing this in Django 1.4.3 along with Python 2.7.2. I had something like this: import operator from django.conf import settings from django.db import models from django.db.models import Q from django.contrib.auth.models import User, Group def query_group_lkup(group_name): return Q(user__user__groups__name__exact=group