Django query for many to many relationship - python

I have following two models
class Questionnaire(models.model)
name = models.CharField(max_length=128, null=True, blank=True)
type = models.CharField(max_length=128,choices=questionnaire_choices)
class TestPopulation(models.Model)
user = models.ForeignKey(User, blank=True, null=True)
age = models.CharField(max_length=20, blank=True, null=True)
education = models.CharField(max_length=50, blank=True, null=True,
choices=EDUCATION_CHOICES)
questionnaire = models.ManyToManyField(Questionnaire, blank=True, null=True)
Now how can i get number of questionnaires for the specific user (logged in user). ?

test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()

questionnaire.objects.filter(test_population__user=user).count()

Related

Django model ordering in another models

I can't find the answer to the following question about learning application building:
I have task model, which has one-to-many relations with other models: text_message, image_message, video_message, quiz_message, web_page_message (let's call them blocks) and I want to allow the user to choose the order in which these blocks will be sent.
The issue is that if I just add small integer field called 'order' in these blocks' classes - user still can choose a number that would be much bigger than the overall number of existing blocks.
So what is the best way to make such ordering?
Thank you for your answers.
UPD.:
Sorry if the code is not perfect, it is my first real Django project.
Added my models.
Questions: 
How to make an order through all these messages?
How to design models in such a way to give the ability to the user to change this ordering?
 
class task(models.Model):
employees_appointed_id = models.ManyToManyField(profile, related_name='task_to_appointed_users')
employees_finished_id = models.ManyToManyField(profile, related_name='task_to_users_finished', blank=True, null=True)
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='who_created_task')
description = models.TextField(max_length=1000)
created_datetime = models.DateTimeField(models.DateTimeField(auto_now=True))
deadline = models.DateTimeField(blank=True, null=True)
title = models.CharField(max_length=55)
course = models.ForeignKey('course', on_delete=models.CASCADE)
mentor = models.ManyToManyField(profile, blank=True, null=True, related_name='task_to_profile')
class text_message(models.Model):
text = models.CharField(max_length=3900)
number_by_order = models.IntegerField()
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='message_to_task')
creator_user_id = models.ForeignKey('profile', on_delete=models.CASCADE, related_name='message_to_creator_user')
course_id = models.ForeignKey('course', on_delete=models.CASCADE, related_name='messages_to_course')
created_datetime = models.DateTimeField(auto_now=True)
class video_message(models.Model):
description = models.CharField(max_length=1024)
media = models.ForeignKey('media', on_delete=models.CASCADE)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='video_message_to_task')
class web_page_message(models.Model):
link = models.CharField(max_length=255)
description = models.TextField(max_length=2000, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='web_page_to_task')
class image_message(models.Model):
media = models.ForeignKey('media', on_delete=models.CASCADE)
description = models.TextField(max_length=1024)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='image_message_to_task')
class quiz_message(models.Model):
question = models.CharField(max_length=300)
option_1 = models.CharField(max_length=100)
option_2 = models.CharField(max_length=100)
option_3 = models.CharField(max_length=100, blank=True, null=True)
option_4 = models.CharField(max_length=100, blank=True, null=True)
option_5 = models.CharField(max_length=100, blank=True, null=True)
option_6 = models.CharField(max_length=100, blank=True, null=True)
option_7 = models.CharField(max_length=100, blank=True, null=True)
option_8 = models.CharField(max_length=100, blank=True, null=True)
option_9 = models.CharField(max_length=100, blank=True, null=True)
option_10 = models.CharField(max_length=100, blank=True, null=True)
explanation = models.CharField(max_length=200, blank=True, null=True)
task = models.ForeignKey('task', on_delete=models.CASCADE, related_name='quiz_message_to_task')

Django many to many filter

I have many to many field in user model where one user can have multiple roles for example admin, patient, doctor and others. now I want to query data to get users with admin and all other roles and not doctor and patient role. I am using this
User.objects.exclude(roles__code_name__in=['pt', 'doc'])
now my one user signs up as patient too so he has admin and patient role both now i am unable to get him by using above query. so concluding... if user has two roles if one of it is patient and he has any other role too i want to get him too. what should i do? Thanks in advance
UPDATE
class User(AbstractBaseUser):
username = models.CharField(max_length=30, unique=True)
email = models.EmailField(max_length=60, blank=True, null=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
cnic = models.CharField(max_length=13, unique=True)
mobile = models.CharField(max_length=11, unique=True)
dob = models.DateField(blank=True, null=True)
full_name = models.CharField(max_length=90, blank=True, null=True)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_path, null=True, blank=True, default=get_default_profile_image_path)
next_of_kin_name = models.CharField(max_length=60, blank=True, null=True)
next_of_kin_mobile = models.CharField(max_length=11, blank=True, null=True)
is_delete = models.BooleanField(default=False)
status = models.IntegerField(default=0)
contact = models.CharField(max_length=10, blank=True, null=True)
hospital = models.ForeignKey('Hospital', on_delete=models.SET_NULL, blank=True, null=True)
roles = models.ManyToManyField('Role', related_name='users')
is_staff = models.BooleanField(default=False)
balance = models.PositiveIntegerField(default=0)
gender = models.CharField(max_length=10, choices=gender_choices, default=gender_choices[0][0])
phone_verified = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.ForeignKey('self', related_name='+', blank=True, null=True, on_delete=models.CASCADE)
This is my model it has roles as many to many field. i have multiple roles like doctor, patient, admin and many others custom created roles with custom permissions. I have a view where i want to get data of users that are not patients or doctors. everything was working fine until one of my admin user decides to sign up as patient so he has now both patient and admin role and now i am unable to get him by using above mentioned query
Eureka. This solution is working fine for me idk if it's the ideal approach bit is working at the moment. Thanks #all
User.objects.annotate(num_roles=Count('roles')).exclude(Q(id=self.request.user.id) | Q(is_delete=True) | Q(roles__code_name__in=['pt', 'doc', 'su']) & Q(num_roles=1)).order_by('-id')

Two dependent conditions in exclude DJANGO

I want to check whether the current user already has the same movie id in his personal list or not. If he has it then I want to exclude that movie from my trending list.
I want it to be something like this.
views.py
trending = list(Movies.objects.exclude(mid in mymovies WHERE uid = request.user.id))
models.py
class Movies(models.Model):
mid = models.CharField(max_length=255, primary_key=True)
title = models.CharField(max_length=255, null=True, blank=True)
rating = models.CharField(max_length=5, null=True, blank=True)
type = models.CharField(max_length=255, null=True, blank=True)
genre = models.CharField(max_length=255, null=True, blank=True)
rdate = models.CharField(max_length=255, null=True, blank=True)
language = models.CharField(max_length=255, null=True, blank=True)
cover = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
sequal = models.CharField(max_length=255, null=True, blank=True)
trailer = models.CharField(max_length=255, null=True, blank=True)
year = models.CharField(max_length=5, null=True, blank=True)
objects = models.Manager()
def __str__(self) -> str:
return self.title
class MyMovies(models.Model):
mid = models.ForeignKey(Movies, on_delete=CASCADE)
uid = models.ForeignKey(User, on_delete=CASCADE, null=True, blank=True)
watched = models.BooleanField()
date = models.DateTimeField(auto_now_add=True)
objects = models.Manager()
You can .exclude(…) with:
trending = Movies.objects.exclude(mymovies__uid=request.user)
If you specified a related_query_name=… [Django-doc] or a related_name=… [Django-doc], then you need to use that to make a JOIN with your Movies model:
trending = Movies.objects.exclude(related_name_of_fk__uid=request.user)
Note: normally a Django model is given a singular name, so MyMovie instead of MyMovies.
Note: Normally one does not add a suffix _id to a ForeignKey field, since Django
will automatically add a "twin" field with an _id suffix. Therefore it should
be user, instead of uid.

How to write a self referencing Django Model?

I have a Django model "Inspection" which has:
InspectionID (PK)
PartID
SiteID
Date
Comment
Report
Signiture
I want to be able to have a one to many relationship between the inspection ID and date. So one ID can have inspections at many dates. How would I do this? I currently have the following:
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
I thought about using models.ForeignKey but I really don't know how to implement that properly in this situation.
I want to be able to have a one to many relationship between the inspection ID and date.
You create an extra model, like:
class InspectionDate(models.Model):
inspection = models.ForeignKey(
Inspection,
on_delete=models.CASCADE,
related_name='inspectiondates'
)
date = models.DateField()
You thus can create InspectionDates for a given Inspection.
Or if you want to add extra data, it might be better to define an InspectionGroup model:
class InspectionGroup(models.Model):
pass
class Inspection(models.Model):
id = models.AutoField(primary_key=True, unique=True, db_column='InspectionId')
inspectiongroup = models.ForeignKey(InspectionGroup, on_delete=models.CASCADE, db_column='InspectionGroupId')
part = models.ForeignKey('Part', on_delete=models.CASCADE, db_column='PartId')
site = models.ForeignKey('Site', on_delete=models.CASCADE, db_column='SiteId')
date = models.DateField(db_column='Date')
comment = models.CharField(max_length=255, blank=True, db_column='CommentId')
report = models.FileField(upload_to='docs', null=True, blank=True, db_column='ReportId')
signiture = models.CharField(max_length=255, blank=True, db_column='Signature')
Note: the name of attributes are normally written in snake_case [wiki], not in PerlCase or camelCase.
you may store 'self Foriegnkey' as
class Inspection(models.Model):
InspectionID = models.IntegerField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE)
Date = models.DateField(auto_now=False, auto_now_add=False)
Comment = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signiture = models.CharField(max_length=255, blank=True)
inspection_id = models.ForeignKey('self', null=True, blank=True)

create custom role in django to employees

I have created a role model for Employee so that employee will be assigned to control
the overall app based on his/her role. I mean if the role of employee is given can_create_only, then the employee should be able to create inventory, orders, items etc and if employee is given can_create_edit_and_delete, then the employee would be like one of the admin and etc. For this I have designed the model as below but I want to know what is the best way to handle such and why?
Should I go with middleware or decorator way? Can anyone give me an example, please?
class Role(models.Model):
name = models.CharField(max_length=100, blank=False, null=False)
class Meta:
verbose_name = 'Role'
verbose_name_plural = 'Roles'
class Employee(models.Model):
office = models.ForeignKey(
OfficeSetup, blank=False, null=False, on_delete=models.CASCADE)
name = models.CharField(max_length=150, blank=False, null=False)
designation = models.ForeignKey(Designation, blank=False, null=False)
section = models.ForeignKey(DepartmentSetup, blank=True, null=True)
phone_number = models.CharField(max_length=150, blank=True, null=True)
mobile_number = models.CharField(max_length=150, blank=True, null=True)
email = models.EmailField(max_length=150, blank=False, null=False)
gender = models.CharField(
max_length=4, choices=GENDER, blank=True, null=True)
role = models.ForeignKey(Role, blank=True, null=True)
username = models.CharField(max_length=100, blank=False, null=False)
password = models.CharField(max_length=100, blank=False, null=False)
avatar = models.ImageField(
null=True, blank=True, upload_to=upload_employee_image_path)
class Meta:
verbose_name = 'Employee'
verbose_name_plural = 'Employees'
def __str__(self):
return self.name
When creating an employee by admin, the username, password and email, the admin provides will create a new user instance along with the employee
Django comes with Groups and permissions which provides all most everything you are looking for.
This may help you - How do I use Django groups and permissions?
Django documentation - https://docs.djangoproject.com/en/1.11/topics/auth/

Categories