Filtering a QuerySet With another QuerySet - python

Hi i'm not very good at English but i'll try to explain myself the best i could. I'm using python and Django to create a web project.
I have this 4 models (this is the best translation i can do of the tables and fields):
class Humans (models.Model):
name = models.CharField(max_length=15)
surname = models.CharField(max_length=15)
doc_num = models.CharField(max_length=11)
...
class Records (models.Model):
closing_state = models.CharField(max_length=2)
...
humans = models.ManyToManyField(Humans, through='Reco_Huma')
class Reco_Huma (models.Model):
id_record = models.ForeignKey(Records)
id_human = models.ForeignKey(Humans)
categorys = models.CharField(max_length=2)
reserv_identity = models.CharField(max_length=2)
repre_entity = models.CharField(max_length=2)
class Observations (models.Model):
id_record = models.ForeignKey(Records)
text = models.CharField(max_length=80)
category = models.CharField(max_length=2, choices=CAT)
Now given a doc_num from Humans, a text from Observations i want to get a QuerySet Of all the Records.
To clarify i first do this:
q1 = Reco_Huma.objects.filter(id_human.doc_num=x)
q2 = Observations.objects.filter(text=y)
both query-sets give me a list of id_record and then i want to connive that lists and filter the Records table with that id_record's
I hope you can understand me
Thanks in advance

To rephrase your query, you want all the Records associated with a certain Human and which have a certain Observation. So it should be:
result = Records.objects.filter(observations__text=y, humans__doc_num=x)
As a general rule, if you want to end up with a certain type of object, it helps to start from there in your query.

Related

Django: Retrieving the number of objects after applying distinct() method

I have a course model which looks like:
class Course(models.Model):
course_code = models.CharField(max_length=20)
course_university = models.CharField(max_length=100)
course_instructor = models.CharField(max_length=100) # lastname
course_instructor_fn = models.CharField(max_length=100) # firstname
"""
More fields are here
"""
Now I have selected instructors for each university using:
qs = Course.objects.filter(course_university__iexact=uni).order_by('course_instructor','course_instructor_fn','course_university').distinct('course_instructor','course_instructor_fn','course_university')
My intention is to now count each the distinct course_code for each instructor using an aggregate Count() function:
so I am trying to basically do:
new_qs = Course.objects.filter(id__in=qs).annotate(course_count=Count('course_code', distinct=True).values_list('course_instructor_fn', 'course_instructor', 'course_count')
However, currently, I only get 1 for user_count no matter how many courses each instructor has.
My intention is to get the number of courses each instructor offers. How can I do this successfully?

Django chain multiple queries in view

I have three models:
Course
Assignment
Term
A course has a ManyToManyField which accesses Django's default User in a field called student, and a ForeignKey with term
An assignment has a ForeignKey with course
Here's the related models:
class Assignment(models.Model):
title = models.CharField(max_length=128, unique=True)
points = models.IntegerField(default=0, blank=True)
description = models.TextField(blank=True)
date_due = models.DateField(blank=True)
time_due = models.TimeField(blank=True)
course = models.ForeignKey(Course)
class Course(models.Model):
subject = models.CharField(max_length=3)
number = models.CharField(max_length=3)
section = models.CharField(max_length=3)
professor = models.ForeignKey("auth.User", limit_choices_to={'groups__name': "Faculty"}, related_name="faculty_profile")
term = models.ForeignKey(Term)
students = models.ManyToManyField("auth.User", limit_choices_to={'groups__name': "Student"}, related_name="student_profile")
When a user logs in to the page, I would like to show them something like this bootstrap collapse card where I can display each term and the corresponding classes with which the student is enrolled.
I am able to access all of the courses in which the student is enrolled, I'm just having difficulty with figuring out the query to select the terms. I've tried using 'select_related' with no luck although I may be using it incorrectly. So far I've got course_list = Course.objects.filter(students = request.user).select_related('term'). Is there a way to acquire all of the terms and their corresponding courses so that I can display them in the way I'd like? If not, should I be modeling my database in a different way?
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values
You could use values or values_list here to get the fields of the related model Term.
For example expanding on your current request:
To retrieve all the Terms' name and duration for the Courses in your queryset
Course.objects.filter(students = request.user).values('term__name', 'term__duration')
I am not sure what the fields are of your Term model, but you would replace name or duration with whichever you are trying to get at.
I think it helps you
terms = Terms.objects.filter(....) # terms
cources0 = terms[0].course_set.all() # courses for terms[0]
cources0 = terms[0].course_set.filter(students=request.user) # courses for terms[0] for user

Get all teachers that have at least 1 subject on table - Django Query Set

I Would like to get all the Teachers that have at least 1 subject. Currently I'm using...
user = users.objects.all().order_by('-karma')[:100]
Because people who does not have any subjects related is a Student.
Here is my models.py
class subjects(models.Model):
id_user = models.IntegerField(db_column='ID_user') # Field name made lowercase.
s = models.CharField(max_length=90)
def __unicode__(self):
return self.s
class Meta:
db_table = 'subjects'
class users(models.Model):
email = models.EmailField(max_length=160)
nick = models.CharField(unique=True, max_length=60)
karma = models.IntegerField(max_length=11)
pass_field = models.CharField(db_column='pass', max_length=160)
One option is to do this in two steps:
get id_user list from subjects model with the help of values_list():
user_ids = subjects.objects.values_list('id_user', flat=True).distinct()
get all users by the list of id_users using __in:
print users.objects.filter(pk__in=user_ids)
Also, since models are not related, you can make a raw query that would do the same in one go.

Copy or clone an object instance in Django/Python

I've following scenario:
class CourseTemplate(models.Model):
title = models.CharField(max_length=70)
teacher = models.ForeignKey(User)
description = models.TextField()
max_students = models.IntegerField()
sessions = models.ManyToManyField(CourseSession) # e.g. Session 1 Introduction, Session 2 Basics, etc.
rating = models.ManyToManyFields(StudentRating)
date_added = models.DateTimeField()
class CourseEnrollment(models.Model):
course = models.OneToOneField(CourseTemplate) # Each enrollment needs a new CourseTemplate Instance, so I can track it
students = models.ManyToManyField(User)
Class CourseSession(models.Model):
title = models.CharField(max_length=50)
date = models.DateTimeField()
details = models.CharField(max_length=100)
address = models.TextField()
#parent_course = models.ForeignKey(CourseTemplate)
class StudentRating(models.Model):
student = models.ForeignKey(User)
rating = models.IntegerField()
#course = models.ForeignKey(CourseTemplate)
Now a teacher (=User) can create a CourseTemplate with all the required details first. After it's saved, he can create a concrete "enrollment" for e.g. this semester with 5 sessions. Maybe he changes after 8 enrollments some details (e.g. CourseTemplate.description or the course now only has 7 sessions instead of 8).
I'd like to have a 1:1 relationship between each CourseTemplate instance and each CourseEnrollment, so I can see for example:
- Teacher X had 2012 three CourseEnrollments, two of them were the same or
- which rating has he received for his second course.
The presented "Template" should always be the "newest", so I'd just need to get the latest instance by CourseTemplate.date_added.
Does anyone know how I can avoid this problem?
Thanks a lot!
You can duplicate any existing django model instance by clearing its primary key, and then saving it again.
ct = CourseTemplate.objects.all()[0]
print ct.pk
# some original pk
ct.pk = None
ct.save()
print ct.pk
# will be a new auto-incremented

GeoDjango: Sort by country of the geolocation

Hi Stackoverflow people,
I have a model which contains projects with the corresponding geolocation:
class Project(models.Model):
name = models.CharField(_('Project Name'), max_length=100, null=True, blank=True)
geolocation = models.PointField(_('Project Location'))
...
In addition, another model is representing a shapefile with the country borders:
class WorldBorder(models.Model):
name = models.CharField(max_length=50)
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
How can I do a query on Project and order the results by the country name of the geolocation?
A query like
d = Project.objects.all().order_by(geolocation__name)
does not work since geolocation is not a Foreignkey. Do I really have loop through all projects and determine the country manually like in my example below?
projects = Project.objects.all()
result = []
for project in projects
country = WorldBorder.objects.filter(mpoly__contains = project.geolocation)
foo = [project.name, country]
result.append(foo)
# now sort the list according to the country
result = sorted(result, key=itemgetter(1))
There should be a more professional and elegant solution? Any suggestions from the experienced Python people? Can I use joins for that purpose?
Thank you for your suggestions!

Categories