Django get data from multiple tables - python

I want to fetch and display details(name_project, user_name) from both tables Project and User1
models.py
class Project(models.Model):
name_project = models.CharField(max_length=50)
leader = models.ForeignKey('User1', default='')
category_project = models.CharField(max_length=50)
class User1(models.Model):
user_name = models.CharField(max_length=30)
mail = models.EmailField(max_length=50)
password = models.CharField(max_length=50)
views.py
def list_project(request):
queryset = Project.objects.raw(
'SELECT scrum_rest_project.id, scrum_rest_project.name_project, scrum_rest_user1.user_name FROM scrum_rest_user1,scrum_rest_project WHERE scrum_rest_user1.id = scrum_rest_project.leader_id')
queryset = serializers.serialize('json', queryset)
return HttpResponse(queryset, content_type="application/json")
but it displays only data from Project table in the json file, I want to display data from User1 table also

You should use select related feature :
Project.objects.select_related().all()

Why are you using raw SQL? Learn Querysets.
1. Using Querysets:
projects = Project.objects.select_related('leader').all()
for project in projects:
print project.name, project.leader.user_name
Note: select_related creates join with User1 and saves you extra SQL queries when accessing User1 model
2. get only list of leader and project name.
project_list = Project.objects.select_related('leader')\
.values_list('name', 'leader__user_name')

Related

Django: how to use .filter( ) method in django?

I am trying to display quiz only for users that are registered in a particular course, i.e if a user is registered in a Frontend Crash Course i want them to see only the quiz related to that course they are registered in, and not all the quiz from the db.
i have a model UserCourse where i am storing all the courses a user have enrolled in, when i try filtering by that models while user_course is get like this below
user_course = UserCourse.objects.get(user=request.user)
quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))
i get this error get() returned more than one UserCourse -- it returned 3! Now i have changed .get() to .filter() like this
user_course = UserCourse.objects.filter(user=request.user)
quizzes = Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))
i then get this error The QuerySet value for an exact lookup must be limited to one result using slicing.
What is the right way to write this query.
models.py
class UserCourse(models.Model):
user = models.ForeignKey(User , null = False , on_delete=models.CASCADE)
course = models.ForeignKey(Course , null = False , on_delete=models.CASCADE, related_name="usercourse")
class Quiz(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="quizzes")
title = models.CharField(max_length=255)
course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True, related_name="quizzes")
date = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(unique=True)
user_course = models.ForeignKey(UserCourse, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.title
The Problem in the Second Line
user_course = UserCourse.objects.filter(user=request.user)
quizzes=Quiz.objects.filter(course__usercourse=user_course).annotate(questions_count=Count('questions'))
remember that when You are using filter you get QuerySet not one object
if you want to return the quizes those related to user_course_queryset you can use __in filter
print(user_course) # print it to understand more
quizzes=Quiz.objects.filter(course__usercourse__in=user_course)
this will Return every Quiz Related to the QuerySet objects

how can we update one to one relationship models db data from django?

i am new to django and i created onetoOneField relationship model with inbuilt User model of django but i cant figure out how can i update that model class table value.
My model
class category(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
TYPES = [
("BASIC","BASIC"),
("PLUS","PLUS"),
("PRO","PRO")
]
User_Type = models.CharField(max_length=40,choices=TYPES,default="BASIC")
Product_Limit = models.IntegerField(default=0)
Amount_Paid = models.IntegerField(default=0)
Tried these 2 cases but getting some error
#key = category.objects.update_or_create(id=request.user.id,User_Type= request.user.category.User_Type,Product_Limit=2,Amount_Paid=request.user.category.Amount_Paid)
user = request.user.category.update_or_create(Product_Limit=10)
Try this:
category = Category.objects.filter(user=request.user).update_or_create(
user=user, Product_Limit=10
)
This will make two SQL queries:
First, Django will make a SELECT ... FROM category WHERE user_id = .... As category and user has a one to one relationship, this should return 0 or 1 row.
If the first query has no record, Django will make an INSERT INTO category query with user_id=request.user.id and Product_Limit=10, the other fields following the default values.
If the first query has a record, Django will make a UPDATE category SET user_id = ..., Product_Limit = ... WHERE user_id = ... query to update the Product_Limit field.

How to write a complex Mysql Query in Django

I am new to Django and I am working on a small module of a Django application where I need to display the list of people who have common interest as that of any particular User. So Suppose if I am an user I can see the list of people who have similar interests like me.
For this I have 2 models :
models.py
class Entity(models.Model):
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class UserLikes(models.Model):
class Meta:
unique_together = (('user', 'entity'),)
user = models.ForeignKey(User)
entity = models.ForeignKey(Entity)
def __str__(self):
return self.user.username + " : " + self.entity.name
So in the Entity Table I store the Entities in which user can be interested Eg : football, Music, Code etc.
and in the UserLikes I store the relation about which user likes which entity.
Now I have a Query to fetch details about which user has maximum interest like any particular user :
SELECT y.user_id, GROUP_CONCAT(y.entity_id) likes, COUNT(*) total
FROM likes_userlikes x
JOIN likes_userlikes y ON y.entity_id = x.entity_id AND y.user_id <> x.user_id
WHERE x.user_id = ?
GROUP BY y.user_id
ORDER BY total desc;
Problem is how do I write this Query using Django Querysets and change it into a function.
# this gives you what are current user's interests
current_user_likes = UserLikes.objects.filter(user__id=user_id) \
.values_list('entity', flat=True).distinct()
# this gives you who are the persons that shares the same interests
user_similar_interests = UserLikes.objects.filter(entity__id__in=current_user_likes) \
.exclude(user__id=user_id) \
.values('user', 'entity').distinct()
# finally the count
user_similar_interests_count = user_similar_interests.count()
Here the user_id is the user's id you want to query for.
One advice though, it's not good practice to use plural form for model names, just use UserLike or better, UserInterest for it. Django would add plural form when it needs to.

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.

Selecting data from few relational tables based on few conditions in Django

I'm using Django 1.6 with Python 2.7 and I have few related models:
# keys/models.py
class Key(models.Model):
user = models.ForeignKey('auth.User')
is_valid = models.BooleanField()
# entities/models.py
class Entity(models.Model):
user = models.ForeignKey('auth.User')
key = models.ForeignKey('keys.Key')
active = models.BooleanField(default=False)
# profile/models.py
class Profile(models.Model):
user = models.ForeignKey('auth.User')
profile_id = models.PositiveIntegerField(null=True, blank=True)
Is it possible to make a single-line query which would check these conditions:
Key.is_valid must be True
Entity.active must be True
Profile.profile_id must not be null (or None)
The only thing I can pass to that query is request.user.
if you are wanting to get Entity objects:
objects = Entity.objects.filter(active=True,
key__is_valid=True,
user__profile__profile_id__isnull=False)
I think that this is what you need:
Check entity:
entity = Entity.objects.filter(active=True, key__is_valid=True, user=request.user)
Check Profile
profile = Profile.objects.filter(user=request.user, profile_id__isnull=False)

Categories