django-queryset

How does one find the entities in a Django query set that are not in another specified query set?

亡梦爱人 提交于 2019-12-05 18:05:33
I am using Django to develop a course registration site for an educational institution. Suppose I have two Django query sets, one that comprises of courses that occupy session 1 (set A) and one that comprises of courses in session 2 (set B): A = session1.courses.all() B = session2.courses.all() There is much overlap between these two query sets. What is an efficient way to obtain the set of courses within set B, but not in set A? I believe this is equivalent to taking out the intersection of the two sets from set B. Thank you! A.exclude(pk__in = B) should work Starting from version 1.11 ,

Django filter datetime base on date only

℡╲_俬逩灬. 提交于 2019-12-05 15:54:07
问题 I'm trying to filter the query set in the BaseDatatableView on a date that's entered in by the user in the following format: mm/dd/yyyy. So start_date is in that format and will get converted to a datetime with strptime, see below. I'd like to compare it to exactly a date datetimefield in the db, but i'd like to match the month, day, year exactly, disregarding the time. This is what I have so that doesn't work. class AppointmentListJson(LoginRequiredMixin, BaseDatatableView): .... start_date

Django: Generating a queryset from a GET request

元气小坏坏 提交于 2019-12-05 14:47:55
I have a Django form setup using GET method. Each value corresponds to attributes of a Django model. What would be the most elegant way to generate the query? Currently this is what I do in the view: def search_items(request): if 'search_name' in request.GET: query_attributes = {} query_attributes['color'] = request.GET.get('color', '') if not query_attributes['color']: del query_attributes['color'] query_attributes['shape'] = request.GET.get('shape', '') if not query_attributes['shape']: del query_attributes['shape'] items = Items.objects.filter(**query_attributes) But I'm pretty sure there's

simple way for QuerySet union and subtraction in django?

陌路散爱 提交于 2019-12-05 13:02:50
问题 Consider two QuerySet objects of the same class. Is there a simple way to unify them into a single QuerySet by calculating the union? Also, is there a simple way to subtract them? Removing all elements that appear in both sets from one of the sets? 回答1: Going back to django's documentation, you can: new_query_set = query_set_1 | query_set_2 This works as a logical OR which is actually addition without duplicates. This answers the addition aspect and AFAIK does not hit the db at all ! new

Django - Unique list from QuerySet

空扰寡人 提交于 2019-12-05 12:44:29
问题 I have a filtered QuerySet which has a ManyToMany field 'Client'. I want to create a unique dict of all the Client objects in the query set so: Projects Queryset: - Project1.client = <Client: 1> - Project2.client = <Client: 1> - Project3.client = <Client: 2> - Project4.client = <Client: 2> - Project5.client = <Client: 3> class Project(models.Model): client = models.ForeignKey(Client, blank=True, null=True) I want to end up with a dict of client objects: {<Client: 1>,<Client: 2>,<Client: 3>}

Django Query extremely slow

社会主义新天地 提交于 2019-12-05 11:40:56
i got a problem with an Django application. Queries on the model Scope are extremly slow and after some debugging i still got no clue where the problem is. When i query the db like scope = Scope.objects.get(pk='Esoterik I') in django it takes 5 to 10 seconds. The database has less than 10 entries and an index on the primary key. so it is way too slow. When executing the an equivalent query on the db like SELECT * FROM scope WHERE title='Esoterik I'; everything is ok, it takes only about 50ms. Same problem happens if i do a query with a set of results like scope_list = Scope.objects.filter

How to aggregate computed field with django ORM? (without raw SQL)

久未见 提交于 2019-12-05 11:38:15
I'm trying to find the cumulated duration of some events, 'start' and 'end' field are both django.db.models.DateTimeField fields. What I would like to do should have been written like this: from django.db.models import F, Sum from my.models import Event Event.objects.aggregate(anything=Sum(F('start') - F('end'))) # this first example return: # AttributeError: 'ExpressionNode' object has no attribute 'split' # Ok I'll try more SQLish: Event.objects.extra(select={ 'extra_field': 'start - end' }).aggregate(Sum('extra_field')) # this time: # FieldError: Cannot resolve keyword 'extra_field' into

how to use __year and __in in the same query?

时光怂恿深爱的人放手 提交于 2019-12-05 11:07:04
So here's what I'm trying to do. I've a list with years inside, for instance years = [2002, 2003, 2004] and I've a SomethingModel with a DateField I want to do a query that will return me all the objects that belongs to that year: I known this work: SomethingModel.objects.filter(date__year=2003) SomethingModel.objects.filter(date__in=[list with dates]) So I've tried this: SomethingModel.objects.filter(date__year__in=years) but this return me this error: FieldError: Join on field 'date' not permitted. Did you misspell 'year' for the lookup type? Does anyone has any idea how to do this? In a

Django Count and Sum annotations interfere with each other

独自空忆成欢 提交于 2019-12-05 06:54:00
While constructing a complexe QuerySet with several annotations, I ran into an issue that I could reproduce with the following simple setup. Here are the models: class Player(models.Model): name = models.CharField(max_length=200) class Unit(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='unit_set') rarity = models.IntegerField() class Weapon(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='weapon_set') With my test database, I obtain the following (correct) results: Player.objects.annotate(weapon_count=Count('unit

Django JOIN query without foreign key

半城伤御伤魂 提交于 2019-12-05 06:34:41
Is there a way in Django to write a query using the ORM, not raw SQL that allows you to JOIN on another table without there being a foreign key? Looking through the documentation it appears in order for the One to One relationship to work there must be a foreign key present? In the models below I want to run a query with a JOIN on UserActivity.request_url to UserActivityLink.url. class UserActivity(models.Model): id = models.IntegerField(primary_key=True) last_activity_ip = models.CharField(max_length=45L, blank=True) last_activity_browser = models.CharField(max_length=255L, blank=True) last