Questions tagged [django-orm]

0

votes
1

answer
29

Views

Filter on relation field in Django ORM

I have a model Media that has a relationship to a model UserMedia (user ratings). Also there's a model called UserMatchScore (match scores of users) that is relevant to the question. In a view I am querying the Media table, in this view there's an option to only get the media that my matches have ra...
Ben Gosub
1

votes
1

answer
682

Views

Dynamic field name in queryset annotation

I need to rename output field name with incoming variable value. There is a function: def metric_data(request, test_id, metric): metric_name = metric data = ServerMonitoringData.objects. \ filter(test_id=test_id). \ annotate(timestamp=RawSQL("((data->>%s)::timestamp)", ('timestamp',))).\ annotate(me...
v0devil
1

votes
1

answer
25

Views

Django sum on query set

I have a queryset in django with condition as follows: query_set = MyModel.objects.annotate(TWWByRuns=( Case( When(Q(toss_winner=F('winner')) & Q(win_by_runs=0), then=1), output_field=FloatField(), default=0) ) ).values('TWWByRuns') I would like to use django built-in sum function to add whenever th...
Laxman
1

votes
1

answer
329

Views

Duplicate save in Django transaction causing InternalError instead of IntegrityError

I am using PostgreSQL as my backend with psycopg2, and I'm noticing something that seems strange to me. My set up is as follows: class ParentModel(models.Model): field1 = models.IntegerField() class ChildModel(ParentModel): field2 = models.IntegerField(unique=True) When I try to save a ChildModel o...
acjay
1

votes
1

answer
66

Views

Filter by twice-removed ForeignKey objects

I have the following models: User, UserProfile, and SalesCompany Relationship: Every User has a UserProfile and every UserProfile has a SalesCompany. I need to get all Users at SalesCompanys with more than one UserProfile. Is there a more efficient way to do it than my following solution? Some combo...
Gady
1

votes
1

answer
174

Views

Get the lowest price list on an article->product relationship

I think the title is no very accurate but I don't know how to better describe it. My model looks like this: class Articles(models.Model): id = models.IntegerField(primary_key=True) supplier = models.CharField(max_length=765, blank=True) ref = models.CharField(max_length=180, blank=True) ean = models...
Nacho
1

votes
1

answer
514

Views

querying parent in model inheritance in django many-to-many by through keyword

I have the following problem: My models are set up similarly to the following scenario class Membership(models.Model): user = models.ForeignKey(User) verified = models.BooleanField() class ClubMembership(Membership): club = models.ForeignKey(Club) class ForumMembership(Membership): forum = models.Fo...
Kristian
1

votes
1

answer
615

Views

Django: Getting the most recent distinct objects

Supposing I have a WeatherReport object with fields date, temperature, and city. I want to get all the most recent WeatherReport objects for each city. I think I would do something like WeatherReport.objects.order_by('-date').distinct('city') But this fails, returning the error ProgrammingError: SEL...
masonjarre
1

votes
1

answer
596

Views

Django, adding item to manytomany within custom save method not working in admin

I am sure this is something stupid that I cannot see, but here is what I have def save(self, *args, **kwargs): print self.sites.all() super(Article, self).save(*args, **kwargs) self.sites.add(Site.objects.get(pk=1)) print self.sites.all() Which prints [, ] [, , ] but site1.co.nz is not being persist...
James Lin
1

votes
1

answer
287

Views

Order a Django QuerySet by a specific ManyToMany Object

I have two classes - Arzt and Fachbereich - related by a ManyToMany relationship through ArztFachbereich. class Fachbereich(FachbereichUndArztFachbereiche): name = models.CharField(unique=True, max_length=100) class Arzt(models.Model): name = models.CharField(max_length=500) fachbereich = models.Man...
Sehebo
1

votes
4

answer
440

Views

Can Python Generators be used in Django Views?

Question: Essentially I want to return a unique result from the database everytime a view is called (until I run out of unique objects and have to start over). I was thinking that a simple and elegant solution would be to use a generator to handle this. Is this possible and if so how can this be a...
Buck
1

votes
1

answer
663

Views

Filtering objects in Django based on optional arguments

Many times I find myself writing code similar to: query = MyModel.objects.all() if request.GET.get('filter_by_field1'): query = query.filter(field1 = True) if request.GET.get('filter_by_field2'): query = query.filter(field2 = False) field3_filter = request.GET.get('field3'): if field3_filter is not...
Tzach
1

votes
2

answer
637

Views

How do I add together fields from a manytomanyfield in django?

I am creating a quote-generator in Django. I want to calculate the total of all items, insert it into a field, and save it. The models are as follows: from django.db import models from django.core.urlresolvers import reverse class Product(models.Model): product_name = models.CharField(max_length=50...
RoninDusette
1

votes
1

answer
682

Views

Prefetch object with multiple levels of reverse lookups

I'm on Django 1.7 and have been using the new Prefetch objects which are a great addition. However I seem to be stuck when I need to traverse back more than one relationship. Here is my code: product_types = self.get_queryset().select_related().prefetch_related( 'excise_category__exciseitem_set__uni...
Nathan Crabbe
1

votes
1

answer
4k

Views

Django Many-To-One relationship filter set

I have a couple models setup like so: Group(models.Model): name = models.TextField(max_length=255) Thing(models.Model): location = models.TextField(max_length=255) group = models.ForeignKey(Group) That's just an example to illustrate the relationship, so forgive any syntax errors. My question is, ho...
1

votes
2

answer
1.1k

Views

Django - There is a way to get the current database alias?

I'm working in a django project with multiple databases and I'm searching a way to get the current database alias using an import or method. I've been searching in the documentation, but I haven't find any useful information.
MikeVelazco
1

votes
1

answer
38

Views

Django ORM doesn't save value when referencing to them by child attributes

Today I found something very tricky. I use django 1.7.7 (if this is important). I have two models in relation: Car and Driver. I want to connect with each other instances of car object and driver object. Both objects seems(*) to be already created. In both cases: car = Car.objects.create() car.save(...
noisy
1

votes
2

answer
3.2k

Views

Django annotate a field value to queryset

I want to attach a field value (id) to a QS like below, but Django throws a 'str' object has no attribute 'lookup' error. Book.objects.all().annotate(some_id='somerelation__id') It seems I can get my id value using Sum() Book.objects.all().annotate(something=Sum('somerelation__id')) I'm wondering is...
rix
1

votes
1

answer
351

Views

Annotation causes OperationalError “field isn't in GROUP BY” in some cases

I'm try to annotate a certain model as follows: items = MyModel.objects.all() aggregated_items = items.annotate(Max('othermodel__some_integer_field')) When inspecting aggregated_items I get an OperationalError: Odd thing is, this works perfectly fine on one database server but not on another. I've o...
Pieter
1

votes
1

answer
702

Views

Related Field got invalid lookup: name with content_type__name

I have the following... @receiver(post_save) def po_save(sender, instance, created, **kwargs): Event.objects.get(content_type__name=sender.__name__) Which gives the error: Related Field got invalid lookup: name. It seems to have a problem with content_type__name however I'm use content_type has name...
Prometheus
1

votes
1

answer
1.3k

Views

Django ORM: Filter on timedelta of Datetime fields

I am trying to fetch posts based on the time difference of two DateTimeField()s, say, posts that were deleted in less than 10 minutes after they were posted. class Post(models.Model): ... time_posted = models.DateTimeField() time_deleted = models.DateTimeField(blank=True, null=True) With the above...
omat
1

votes
3

answer
52

Views

How to query django m2m for a single instance that satisfies multiple requirements?

For the sake of example, I have the following Django models: class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Book(models.Model): name = models.CharField(max_length=30) authors = models.ManyToManyField(Author) (because books r...
Brendan
1

votes
1

answer
671

Views

how is Django persistent database connections thread safe?

In django, persistent db connections are implemented by threading.local. This code resides in the class django.db.utils.ConnectionHandler. Since this class is instantiated in django.db.__init.__.py it gets instantiated when we do import django.db. And this would happen somewhere during request/respo...
shreyas
1

votes
2

answer
41

Views

Directly providing foreign key value in django

Consider these two models: class CarType(models.Model): code_name = models.SlugField(primary_key=True) name = models.CharField(max_length=20) class Car(models.Model): name = models.CharField(max_length=30) car_type = models.ForeignKey('CarType') Assume we want to get all sedan cars, instead of this...
MJafar Mash
1

votes
1

answer
75

Views

How can I use an OR-condition in a Django ORM filter? [duplicate]

This question already has an answer here: Django Filters - or? 6 answers Here is my django view: def get_initial_queryset(self): filter_dict={} location=self.request.POST.get('location_id') if location: set_if_not_none(filter_dict, 'port__device__host__location', location) client=self.request.POST....
Vladimir Akkerman
1

votes
1

answer
479

Views

Django ORM: Compare substring

Is there a way to compare the last 10 characters of a column (type string) in database using django ORM query. I want to do something like: foo = '1234567890' result= db.objects.filter(col1[-10:]=foo).values('name') But col1[-10:] doesn't work. Is there any alternative for this? Note: foo can be les...
Habel
1

votes
1

answer
143

Views

Django two inner joins

I am new in Django. I have an mySQL query: SELECT username, foto FROM a INNER JOIN b ON (a.user_id = b.id) INNER JOIN c ON (a.foto_id = c.id) How to write it in Django? models: class b(models.Model): username = models.CharField(max_length=30) email = models.CharField(max_length=30) password = mode...
Bird
0

votes
0

answer
5

Views

How to get multiple values from joined tables

How can I get all the laws from all the courses that an specific user is subscribed? class Law(models.Model): name = models.CharField('Nome', max_length=100) slug = models.SlugField('Atalho') description = models.TextField('Description', blank = True, null=True) class Course(models.Model): name =...
mr.abdo
2

votes
1

answer
20

Views

query to get count, subtotal and total over a date range

Say I have objects with a created_at attribute. I would like to have a query that will result in the counts of created objects on a given date (count_), subtotal of objects up to that date (sub), and the full total of all objects (total_): date | count_ | sub | total_ ------------+--------+-...
minusf
11

votes
2

answer
2.3k

Views

Django QuerySet filter method returns multiple entries for one record

Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria: Blog.objects.filter(entries__title__contains='entry') The results is: [, ] The same blog object is retrieved twice because of JOIN performed to filter objects on related model. What is the right syn...
Yaroslav
1

votes
2

answer
1.4k

Views

Multiply two fields together in django

I have the following query: sales_for_date_for_provider.exclude(sales_or_return='R').values_list('royalty_price', 'conversion_to_usd')) Is it possible to multiple the royalty_price * conversion_to_usd in the query? Or do I need to do a list comprehension or dive into raw SQL?
David542
1

votes
3

answer
54

Views

How to count all users in reverse relationship

Using Django ORM I would like to create a method on Company which returns the User count. This is what I have tried (see company_user_count method): User Model: class AppUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=254, unique=True, db_index=True, ) co...
Prometheus
1

votes
2

answer
616

Views

What minimal files i need to use django ORM

I have python module for doing some stuff and i need to save few items in database. Currenlt i am using raw sql to insert data. But i want to use django ORM for that. I don't need any urls , views etc. all i want is that i can create models and then should be able to save it like user.save() Now i d...
John Kaff
1

votes
2

answer
359

Views

Django ORM filter default value which returns all objects

I have a model Book which has a field year_of_publishing. A user inputs the year and I want to filter the Book's set getting all the books published in that year. year = self.cleaned_data.get('year', SOME_DEFAULT_VALUE) books = Book.objects.filter(year_of_publishing=year) However the user might lea...
Anton Khodak
2

votes
1

answer
590

Views

Django: find all OneToOneFields pointing to a Model

I'm writing routines to inspect an instance and find all its relations (e.g. using instance._meta.get_all_related_objects()) but I can't find a way to get relations involving a OneToOneField. For instance, with these two models: class Main(models.Model): ... class Extension(models.Model): ... main =...
Don
1

votes
2

answer
1.6k

Views

Django QuerySet vs. raw SQL performance considerations

I'm learning Django and its ORM data access methodology and there is something that I'm curious about. In one particular endpoint, I'm making a number of database calls (to Postgres) - below is an example of one: projects = Project.objects\ .filter(Q(first_appointment_scheduled=True) | (Q(active=Tru...
Snowie
5

votes
1

answer
1.2k

Views

Django OneToOneField, ManyToManyField, Foreign Key

I've read many posts on what OneToOneField, ManyToManyField, and Foreign Key are but they aren't very clear. I am very new to Django and python programming, currently trying to develop models. Can someone explain to me in simple language, preferably with example, what they each are?
Rjzheng
4

votes
2

answer
1.6k

Views

Django Queryset - get last related object and filter by it's data

I have two Django Models: class Person(models.Model): unique_id = models.CharField() class PersonData(models.Model): person = models.ForeignKey('Person') phone = models.CharField() email = models.CharField() date = models.DateTimeField() New PersonData objects are added when their information change...
Mark
17

votes
2

answer
4.8k

Views

Determine if an attribute is a `DeferredAttribute` in django

The Context I have located a rather critical bug in Django Cache Machine that causes it's invalidation logic to lose its mind after a upgrading from Django 1.4 to 1.7. The bug is localized to invocations of only() on models that extend cache machine's CachingMixin. It results in deep recursions tha...
nsfyn55
17

votes
1

answer
6.3k

Views

Migrating ManyToManyField to null true, blank true, isn't recognized

I have made a model change from standard = models.ManyToManyField(Standard) to standard = models.ManyToManyField(Standard, blank=True, null=True) South schemamigration for this app doesn't recognize the change? Similar to this question, which is unanswered: South migrations and changes to many-to-...
npradeetw

View additional questions