Django how to get values by user_ID - python

I'm trying to get all of a users reports and pass them to the page template. My question is how do I filter by user_id=1?
views.py
data = report.objects.values()
return render(request,'list.html',data)
models.py
class user(models.Model):
firstname = models.CharField(max_length=250)
lastname = models.CharField(max_length=250)
email = models.CharField(max_length=250)
password = models.CharField(max_length=250)
newsletter = models.BooleanField(default=0)
accountlevel = models.BigIntegerField(default=1)
reportsCreated = models.BigIntegerField(default=0)
class report(models.Model):
user = models.ForeignKey(user, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
dateran = models.DateField()
fromdate = models.DateField()
todate = models.DateField()
state = models.IntegerField()
graphURL = models.CharField(max_length=1000)
reporttype = models.CharField(max_length=250)

In your views.py you can filter values by user id.
Refer following code
data = report.objects.filter(user__id=your_user_id).values()
return render(request,'list.html',data)

Got it to work, I was missing the context,
data = Report.objects.filter(user__id=1).values()
context = {'data': data}
return render(request,'list.html',context)
Thank you call for your help :)

Related

How to get multiple field values, when a foreign key is called in django

I have a Attendance model
class Attendance(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
date = models.DateField()
day = models.CharField(max_length=10)
in_time = models.CharField(max_length=5)
out_time = models.CharField(max_length=5)
Here is the Employee model
class Employee(models.Model):
emp_id = models.CharField(max_length=10,primary_key=True)
emp_type = models.CharField(max_length=50)
name = models.CharField(max_length=100)
epf_no = models.CharField(max_length=10)
nic_no = models.CharField(max_length=15)
appoinment_date = models.DateField()
termination_date = models.DateField()
address = models.CharField(max_length=50)
mobile_no = models.CharField(max_length=15)
email = models.EmailField(max_length=50)
bank_name = models.CharField(max_length=50)
bank_branch = models.CharField(max_length=20)
bank_acc_name = models.CharField(max_length=20)
bank_acc_no = models.CharField(max_length=15)
active_status = models.BooleanField(default=True)
I'm getting data from Attendance model
attendance_record = Attendance.objects.filter(date = date).values()
Here for the employee attribute I'm automatically getting the emp_id field.But I want to get the name field as well
How to do it.?
You can access the name through the employee relation:
attendance_record.employee.name
If you want the name in the attendance_record queryset, you can use F('') expressions.
from django.db.models import Avg, Case, Count, F
Attendance.objects.filter(date=date).annotate(name=F('employee__name')).values()

How to test related models in Django v3

I am trying to test Destination and Comment models and check if they are related in the test.
I have already tested the Destinations models and it pass the test with the approach:
def test_destinations_model(self):
destination = Destinations.objects.create(
tour_title = 'test1',
booking_start_date='2021-05-30',
booking_end_date= '2022-05-30',
price=2000,
description='test1',
author='test1',
image='image.png'
)
destination.save()
self.assertEquals(destination.tour_title, 'test1')
self.assertEquals(destination.booking_start_date, '2021-05-30')
self.assertEquals(destination.booking_end_date, '2022-05-30')
self.assertEquals(destination.price, 2000)
self.assertEquals(destination.description, 'test1')
self.assertEquals(destination.author, 'test1')
self.assertEquals(destination.image, 'image.png')
However, I don't know how to test the Comment model since it is related to the Destinations one. I have done the following approach but the test is failing with the following message:
#message of failing test for test_comment_model
self.assertEquals(destination, comment)
AssertionError: <Destinations: test1> != <Comment: Comment test1 by John>
#Failling test:
def test_comment_model(self):
#post not needed to test as foreignKey
destination = Destinations(
tour_title = 'test1',
booking_start_date='2021-05-30',
booking_end_date= '2022-05-30',
price=2000,
description='test1',
author='test1',
image='image.png'
)
destination.save()
comment = Comment(
post=destination,
name = 'John',
email = 'any#email.com',
comment = 'test1',
created_on = timezone.now(),
active = False,
)
comment.save()
self.assertEquals(destination, comment)
class Destinations(models.Model):
author = models.CharField(max_length=200, unique=False)
tour_title = models.CharField(max_length=250)
description = RichTextUploadingField()
image = models.ImageField(upload_to='tour_images', blank=True)
location = models.CharField(max_length=250)
booking_start_date = models.DateField()
booking_end_date = models.DateField()
price = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return self.tour_title
class Comment(models.Model):
post = models.ForeignKey(Destinations,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
comment = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.comment, self.name)
I am still not sure what exactly you want to test but if you want to check if Comment is related to destination you could check by following
self.assertEquals(destination, comment.post)

django query to get posts from users followed by a user

My models:
class ClientProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client_profile')
follows = models.ManyToManyField(User,
related_name='follows',blank=True)
profile_picture = models.ImageField( blank=True)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
mobile_number = models.CharField(validators=[phone_regex],
max_length=17, blank=True)
dob = models.DateField(auto_now = False, null = True)
profile_summary = models.TextField()
my_career_objective = models.TextField()
educational_qualification = models.CharField(max_length=200)
work_experience = models.IntegerField(blank=True, null=True)
skill_set = models.TextField(blank=True)
address_1 = models.CharField(max_length=300,blank=True)
address_2 = models.CharField(max_length=300,blank=True)
# new fileds
about_me = models.TextField(blank=True)
birthplace = models.CharField(max_length=150,blank=True)
lives_in = models.CharField(max_length=150,blank=True)
occupation = models.CharField(max_length=150, blank=True)
gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True)
marital_status = models.CharField(choices=MARITAL_CHOICES,max_length=150, blank=True,default=1)
religion = models.CharField(max_length=150, blank=True)
political_incline = models.TextField(blank=True)
# other_social_networks = models.TextField(blank=True)
hobbies = models.TextField(blank=True)
favorite_tv_shows = models.TextField(blank=True)
favorite_movies = models.TextField(blank=True)
favorite_games = models.TextField(blank=True)
favorite_music_band_artists = models.TextField("Favorite Music, Bands / Artists", blank=True)
favorite_books = models.TextField(blank=True)
favorite_writers = models.TextField(blank=True)
other_interests = models.TextField(blank=True)
subscription = models.TextField(blank=True, null=True, default="Free")
def __str__(self):
return str(self.user.first_name) + " " + str(self.user.last_name)
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes',blank=True)
is_verified=models.BooleanField(default=False,blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:dashboard')
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type =
ContentType.objects.get_for_model(instance.__class__)
return content_type
I want to display all tasks from logged in user and also all the tasks from all users followed by logged in user.What is the best django query to implement this? the follows field in the ClientProfile model is given as many to many field to depict all users followed by the user.How to write django query with 'or'.Each task points to a user through foreign key 'student' . I want to display all tasks from logged in user and all users followed by logged in user in the homepage
Put a related_name attribute in student field of Task. (let's call it task)
If logged_in_user is your logged in user object then logged_in_user.task would give task of logged_in_user and for user's followers tasks:
tasks = Task.objects.filter(student__in= logged_in_user.follows.all())
Without related_name.
task = Task.objects.filter(Q(student=logged_in_user) | Q(student__in=logged_in_user.follows.all()))
This worked for me :
client=ClientProfile.objects.get(user=request.user)
task = Task.objects.filter
(Q(student=request.user) |
Q(student__in=client.follows.all()))
.order_by('timestamp').prefetch_related('images_set')

How save specific user instance into database using django views

I created models called Interview, Users, Interview_interviewer like wise...
Interview_interviewer table has foreign keys from other models.
I just want to save data from both 2 tables to Interview_interviewer(Without django forms) table which is many to many table. So I just created the views and template for it. When button clicks it save the Interviewers to table along side with the interview. But when do it, It gave me and error called "User matching query does not exist".
/home/govinda/DMG/test3/myapp/views.py in hod_inter_interviewer_2
usr = User.objects.get(id=pid)
What should I do?
class Interview(models.Model):
Time = models.TimeField()
Date = models.DateField()
Venue = models.ForeignKey('Venue')
HOD = models.ForeignKey(User)
Vacancy = models.ForeignKey('Vacancy', on_delete=models.CASCADE)
Department = models.ForeignKey(Department, on_delete=models.CASCADE)
InterviewType = models.ForeignKey(InterviewType, on_delete=models.CASCADE)
Interviewer_Review = models.TextField(blank=True, null=True)
HOD_Review = models.TextField(blank=True, null=True)
HR_Review = models.TextField(blank=True, null=True)
NoOfPasses = models.PositiveIntegerField(blank=True, null=True)
NoOfFails = models.PositiveIntegerField(blank=True, null=True)
NoOfOnHolds = models.PositiveIntegerField(blank=True, null=True)
InterviewNo = models.IntegerField(blank=True, null=True)
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
and
class Users(models.Model):
User = models.OneToOneField(User)
FullName = models.CharField(max_length=100)
Post = models.ForeignKey(Post)
UPhoto = models.FileField(upload_to=User_directory_path,null = True,blank=True)
Department = models.ForeignKey(Department)
UserRole = models.ForeignKey(UserRole)
def __str__(self):
return u'{}'.format(self.User)
and
class Interview_Interviewer(models.Model):
Interview = models.ForeignKey(Interview)
Interviewer = models.ForeignKey(User)
def __str__(self):
return u'{}'.format(self.Interviewer)
views are...
def hod_pre_interviwer_list(request, iid):
inter = Interview.objects.get(id=iid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter, 'a':a})
def hod_inter_interviewer_2(request, iid, pid):
inter = Interview.objects.get(id=iid)
usr = User.objects.get(id=pid)
a = UserRole.objects.get(Role="Interviewer")
viewer = Users.objects.filter(UserRole=a.id)
usr_id = Users.objects.get(User=a.id)
inter_id = inter
person_id = usr_id
form = Interview_Interviewer(Interview=inter_id, Interviewer=person_id)
form.save()
return render(request, 'hod_inter_create_2.html', {'viewer': viewer, 'inter': inter})
urls are...
urlpatterns = [
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/$', hod_pre_interviwer_list, name="inter1"),
url(r'^hod/hod_vacancy/test/part2/inter_list/(\d+)/(\d+)/$', hod_inter_interviewer_2, name="inter2"),
]
template is...
<a type="submit" class="btn btn-primary" href="/hod/hod_vacancy/test/part2/inter_list/{{ inter.id }}/{{ viewer.id }}">Add</a>
Try using named groups in your url patterns
urlurl(r'^hod/hod_vacancy/test/part2/inter_list/?P<iid>[0-9]+)/?P<pid>[0-9]+/$', hod_inter_interviewer_2, name="inter2"),
If that doesn't work then i suggest trying User.object.get(pk=pid) as in most doc examples.
And make sure that there is a user with that id (iid) in the url.
You should also use get_object_or_404 for getting any single object from a model in the view as it gives a more user friendly and appropriate error.

how to select columns from multiple models in django?

models.py
class Custom_user_model(User):
daily_target = models.IntegerField()
monthly_target = models.IntegerField()
yearly_target = models.IntegerField()
weekly_target = models.IntegerField()
call_target = models.IntegerField()
email_target = models.IntegerField()
meeting_target = models.IntegerField()
added_under = models.IntegerField()
profile_pic = models.TextField()
doj = models.DateTimeField(default='')
location_id = models.IntegerField()
locked = models.BooleanField()
default_currency = models.IntegerField()
date_change_permission = models.BooleanField()
deal_back_log = models.BooleanField()
created_date=models.DateTimeField(auto_now_add=True)
role_id=models.ForeignKey('user_Roles')
profile_pic = models.FileField(upload_to='.')
objects = UserManager()
class Deal(models.Model):
a_choices = ((0,'yes'),(1,'no'))
approved = models.IntegerField(choices=a_choices,default=1)
user_id = models.ForeignKey('Custom_user_model')
company_id = models.IntegerField()
contact_id = models.IntegerField()
deal_title=models.CharField(max_length=200)
deal_value = models.CharField(max_length=20)
currency_id = models.IntegerField()
process_id = models.IntegerField()
expected_close_date = models.DateField(default='')
closed_date = models.DateField()
deal_milestone=models.IntegerField()
created=models.DateTimeField(auto_now_add=True)
last_modified=models.DateTimeField(auto_now_add=True)
s_choices = ((0,'active'),(1,'won'),(2,'junk'),(3,'lost'))
status = models.IntegerField(choices=a_choices,default=0)
type = models.CharField(max_length=50, default='deal')
class user_Roles(models.Model):
code = models.CharField(max_length=20)
description = models.CharField(max_length=30)
permitted_menus = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
views.py
Here, i wrote the code to get columns from three models. But
Deal.objects.filter(user_id__role_id_id=1).select_related() returned nothing and Deal.objects.filter(user_id__role_id_id=1).select_related().values() returned the fields from deal model only. It shows 'no fields error', when specifying relationship as values('Custom_user_model__doj').How can i select fields from multiple models?
def get_all_normal_users(request,start_date=None,end_date=None):
query = Deal.objects.filter(user_id__role_id_id=1).select_related().values()
start_date_range = (
# The start_date with the minimum possible time
datetime.datetime.combine(start_date, datetime.time.min),
# The start_date with the maximum possible time
datetime.datetime.combine(end_date, datetime.time.max)
)
query = query.filter(created__range=start_date_range).values()
data_dict = ValuesQuerySetToDict(query)
data_json = json.dumps(data_dict)
return json_response({'status':data_json})
If you want to select related values you have to specify all parameters you want in values(). Otherwise you will get only the foreignkey to your user model. Try adding the values you want from your user model with __:
query = query.filter(created__range=start_date_range).values('approved', ..., 'user_id__daily_target', 'user_id__username')
Btw if you are creating an API you should have a look at django-rest-framework
try this,
Deal.objects.filter(user_id__role_id_id=1, created__range=start_date_range).select_related('user_id').values()
or specify required fields as parameters to values().

Categories

Resources