Django join on multiple foreign fields (left join) - django

I'm using django 1.10 and have the following two models
class Post(models.Model):
title = models.CharField(max_length=500)
text = models.TextField()
class UserPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
approved = models.BooleanField(default=False)
How do I get a list of all the posts including the 'approved' property for the logged in user if exists? So instead of multiple queries, it would be one left join query, pseudo-code:
select * from posts as p
left join user_posts as up
on up.post_id = p.post_id
and up.user_id = 2
Output
post_id | title | text | user_id | approved
1 | 'abc' | 'abc' | 2 | true
2 | 'xyz' | 'xyz' | null | null
3 | 'foo' | 'bar' | 2 | true
I created the models this way because the 'approved' property belongs to the user. Every user can approve/reject a post. The same post could be approved and rejected by other users. Should the models be setup differently?
Thanks
Update:
I'm trying to create a webpage to display all available posts and highlight the ones that the current user approved. I could just list all posts and then for each post check if the 'UserPost' table has a value, if yes get the approved property else ignore. But that means if I have 100 posts I'm making 100 + 1 calls to the db. Is it possible to do 1 call using ORM? If this is not possible, should the models be setup differently?

Then I think you need something like this:
Post.objects.all().annotate(
approved=models.Case(
models.When(userpost_set__user_id=2,
then=models.F('userpost__approved')),
default=models.Value(False),
output_field=models.BooleanField()
)
)

Related

How to get count of subjects taken by each student?

I've two models 'Students' and 'Enrollments'.
The schema for these is as below:
class Students(models.Model):
id = models.AutoField(primary_key=True, unique=True)
name = models.CharField()
class Enrollments(models.Model):
enroll_id = models.AutoField(primary_key=True, unique=True)
student_id = models.ForeignKey(Students, on_delete=models.CASCADE)
subjects = models.charField()
I'm trying to achieve the result of following SQL query in Django Rest Framework, for getting number of subjects enrolled by students (individually).
select
s.id, s.name, count(e.subjects) as count
from Students as s
left outer join Enrollments as e
on e.student_id_id = s.id
group by s.id, s.name, e.subjects
order by count asc;
This query returns result like:
---------------------------
| id | name | count |
---------------------------
| 1 | a | 1 |
| 2 | b | 0 |
| 3 | c | 2 |
---------------------------
Can anyone please help me acheive this kind of result.
Note: I need 0 count students details also.
What you can do is when you are creating a serializer, you can add a serializer method field which will get the count for you.
Add this at the top of your serializer:
count = serializers.SerializerMethodField('get_count')
Then add a function inside your serializer like this:
def get_count(self, obj):
try:
return Enrollments.objects.filter(student_id=obj.id).count()
except:
return None
Finally, add 'count' to your field list. You can then add as many fields as you want. I hope this will get you your desired result. Also don't forget to use "select_related" in the ORM inside your view to reduce the amount of queries.

DJANGO - Using simple history, how can I show both a base model record and a related history group calculation in one query?

I am using the simple history library for my Django project. It's pretty nifty, but I'm having trouble showing aggregated history stats next to a base model object.
Here's what my model looks like:
from django.db import models
from django.contrib.auth.models import User
from simple_history.models import HistoricalRecords
class RepairForm(models.Model):
user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
return_number = models.CharField(max_length=200, unique=True)
status_id = models.ForeignKey(RFormStatus, on_delete=models.DO_NOTHING)
...
history = HistoricalRecords()
def __str__(self):
return self.return_number
The Docs lead me to believe the proper way of accessing historical records is using the history manager. I can get both sets of information I want:
All Forms (base model objects) -
RepairForm.objects.all()
User ID | Return Number | Status ID
-----------------------------------------------------------
33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001
44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002
...
A history calculation (history object)
In this example I am getting the latest event of each form -
RepairForm.history.all()\
.values('return_number').annotate(latest_event_date=Max('history_date'))\
.order_by('return_number')
Return Number | latest_event_date
-----------------------------------------------------------
0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 7/27/2018
5f699795-5119-4dcd-8b94-34f7056e732c | 8/1/2018
...
I feel like this should be possible to do in one query though no? One query that outputs something like this:
User ID | Return Number | Status ID | latest_event_date
------------------------------------------------------------------------------
33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001 | 7/27/2018
44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002 | 8/1/2018
...
you can add a property for example "latest_event_date" that calculates the wanted result.then it is always calculated when you run a query on RepairForm!
#property
def latest_event_date(self):
....

Django view fetching data from two models in a single query

I have two tables in my database which are relevant for this problem:
exercise_state with following fields:
| id | intensity_level | progress | exercise_id | user_id | current_date | user_rating |
auth_user with following fields:
| id | password | last_login | is_superuser | username | first_name | last_name | email | is_staff | is_active | date_joined |
Right now I am fetching some data in my view as follows:
def get_specific_exercise_finish_count(request, exerciseId):
# Number of users who completed a specific exercise
specific_exercise_finish_count = Exercise_state.objects.filter(exercise_id=exerciseId, intensity_level=7).count()
data = {}
data['count'] = specific_exercise_finish_count
return JSONResponse(data)
Now I want to filter those results further for specific set of usernames i.e. usernames those starts with 'yg_' (I have two sets of usernames registered in my system one group starts with 'yg' and the other with 'yg_'). As username is not a field of exercise_state, I am not sure how to proceed.
How can I achieve this?
I solved it with following code of piece, see the extra part in filter statement:
def get_specific_exercise_finish_count_memoryGames(request, exerciseId):
# Number of users who completed a specific exercise
specific_exercise_finish_count_memoryGames = Exercise_state.objects.filter(exercise_id=exerciseId, intensity_level=7, user__username__startswith='yg_').count()
data = {}
data['count'] = specific_exercise_finish_count_memoryGames
return JSONResponse(data)

model inheritance + django admin

I am reusing the News model from cmsplugin_news, just adding some extra fields in my inheriting model. (Multi-table inheritance, just as explained here.
from cmsplugin_news.models import News
class News(News):
departments = models.ManyToManyField('department.Department', blank=True, related_name="news")
On my admin.py I am extending NewsAdmin to set my own form:
class MyNewsAdmin(NewsAdmin):
form = NewsModelForm
Which I have defined in forms.py:
from news.models import News
class NewsModelForm(NewsForm):
class Meta:
model = News
widgets = {
'excerpt': CKEditorWidget(config_name='basic'),
'content': CKEditorWidget(config_name='default')
}
def _get_widget(self):
from ckeditor.widgets import CKEditorWidget
return CKEditorWidget()
The model inheritance seems to work well when I save objects from the shell console. But when I try to create a MyNews object from the django admin and link it to a department, this field is not saved. Or at least this change is not shown anywhere
unicms-testnews=> select * from cmsplugin_news_news;
id | title | slug | excerpt | content | is_published | pub_date | created | updated | link
----+-------+------+---------+---------+--------------+------------------------+-------------------------------+-------------------------------+------
1 | dfad | dfad | | | f | 2013-09-10 13:44:46+02 | 2013-09-10 13:45:04.709556+02 | 2013-09-10 13:57:05.568696+02 |
(1 row)
unicms-testnews=> select * from news_news;
news_ptr_id
-------------
1
(1 row)
unicms-testnews=> select * from news_news_departments;
id | news_id | department_id
----+---------+---------------
1 | 1 | 1
(1 row)
I can't understand anything, can anyone help me please? Thank you very much!
You created a form for News, that also exist in your DB since the model is not abstract, not for MyNews. Thus your current form has no field for the departments attribute, even if you add a widget with an input for it. Do the code bellow instead:
class MyNewsForm(NewsForm):
class Meta:
model = MyNews # instead of just News
...
What Django does in background is to create two relations: the cmsplugin_news_news stores all the News fields, and the news_news_departments stores your new field and is in one-to-one relation with the first relation.

django accessing raw many to many created table fields

Model:
class Subjects (models.Model):
name = models.CharField(max_length=100)
places = models.CharField(max_length=100)
class Student (models.Model):
name = models.CharField(max_length=40)
lastname = models.CharField(max_length=80)
subjects = models.ManyToManyField(Subjects, blank=True)
Django creates appname_student_subjects when I use model above.
appname_student_subjects table looks for example, like this:
id | student_id | subjects_id
-----------------------------------------
1 | 1 | 10
2 | 4 | 11
3 | 4 | 19
4 | 5 | 10
...
~1000
How can I access subjects_id field and count how many times subjects_id exists in the table above (and then do something with it). For example: If subject with id 10 exists two times the template displays 2. I know that I should use "len" with result but i don't know how to access subject_id field.
With foreign keys I'm doing it like this in a for loop:
results_all = Students.objects.filter(subject_id='10')
result = len(results_all)
and I pass result to the template and display it within a for loop but it's not a foreign key so it's not working.
You can access the through table directly.
num = (Students.subjects # M2M Manager
.through # subjects_students through table
.objects # through table manager
.filter(student_id=10) # your query against through table
.count())