Django many to many filter - python

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')

Related

problem with multiple user dependent on each other in Django

I am working with some custom-made user models in Django. They are the following:
myCustomeUser responsible for the primary identity of a user
Industry is a user that will link with OneToOneField to the myCustomeUser
Employee is another user account, which will FK to the myCustomeUser and FK to Industry
my models.py:
class myCustomeUser(AbstractUser):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=20, unique="True", blank=False)
password = models.CharField(max_length=20, blank=False)
is_Employee = models.BooleanField(default=False)
is_Industry = models.BooleanField(default=False)
class Industry(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user')
name = models.CharField(max_length=200, blank=True)
owner = models.CharField(max_length=200, blank=True)
license = models.IntegerField(null=True, unique=True)
industry_extrafield = models.TextField(blank=True)
Now I need to write the model of Employee. There are some conditions also:
It should contain name, National ID, gmail, rank, employee_varified, named fields
This will inherit the myCustomeUser and Industry both
The Industry account user will primarily entry all the data of Employee in the database, except username and password(which are inherited from myCustomeUser)
Later on, the Employee will search his National ID given by the Industry and finish the registration process by creating his username and password.
I have tried the Employee model like this:
class Employee(models.Model):
user = models.ForeignKey(myCustomeUser,primary_key=True, null=True, on_delete=models.CASCADE)
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
National_ID = models.IntegerField(null=True, blank=False, unique=True)
name = models.CharField(max_length=200, blank=False, null=True)
gmail = models.EmailField(null=True, blank=False, unique=True)
rank = models.CharField(max_length=20, blank=False, null=True)
employee_varified = models.BooleanField(default=False, blank=True, null=True)
But the problem with this model is I cannot create any Employee object without giving user (that means username and password), But the Industry user needs to entry their Employee's data, before complete the Employee's registration.
how can I write my Employee model to solve this problem?
If you can't guarantee that a related object will exist when you create an object, you can make the relationship(s) optional.
So in your case, I'd create your model more like;
class Employee(models.Model):
user = models.ForeignKey(
myCustomeUser,
blank=True,
null=True,
on_delete=models.CASCADE
)
industry = models.ForeignKey(
Industry,
blank=True,
on_delete=models.CASCADE
)
national_id = models.IntegerField(
null=True,
blank=False,
unique=True
)
name = models.CharField(
max_length=200,
blank=False,
null=True
)
# ... etc
You may also benefit from having a look through the following site which might help you learn a thing or two about django
https://www.django-antipatterns.com/

user Checkout and guest checkout: best way to use both in Django

Actually I need suggestion about best practice to handle guest checkout and customer checkout.
I have a scenario that 1 order can have multipul products (which is not problem). My order table is like
class Orders(models.Model):
customer= models.ForeignKey(Customer, on_delete=models.CASCADE)
order_number = models.AutoField(primary_key=True)
total_amount = models.DecimalField(max_digits=10, decimal_places=2)
ordertime = models.DateTimeField(auto_now_add=True)
order_status = models.CharField(max_length=50)
is_placed = models.BooleanField(default=False)
and then it is linked to product table like this
class OrderProduct(models.Model):
order=models.ForeignKey(Orders, on_delete=models.CASCADE)
activity = models.ForeignKey(ActivityOrganizer, on_delete=models.CASCADE)
participants=models.IntegerField(default=0)
totalPrice=models.DecimalField(max_digits=10, decimal_places=2)
checkIn = models.DateField()
language = models.CharField(max_length=50, null=False, blank=False)
And my Customer Table is
class Customer(models.Model):
customerProfile = models.OneToOneField(User, on_delete=models.CASCADE)
first_name=models.CharField(max_length=50, null=False, blank=False)
last_name=models.CharField(max_length=50, null=False, blank=False)
email=models.CharField(max_length=50, null=False, blank=False)
mobile_number=models.CharField(max_length=50, null=False, blank=False)
profile_image=models.ImageField(null=True, upload_to='CustomerProfile')
is_customer=models.BooleanField(default=False)
city=models.CharField(max_length=50, null=True, blank=True)
gender=models.CharField(max_length=50, null=True, blank=True)
verification_key = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return str(self.first_name)
Now I want to Enable guest checkouts aswell . then Should I use existing tables of order by allowing Foregin key Null ? Or I should make seprate order tables for this ? What will be best way ?
Based off the information you've presented, I'd make Customer.customerProfile nullable and have it set to None for guest checkouts.

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/

Django UNIQUE constraint failed with OneToOneField while migrate in Django User Model

In database I have already registered 4 persons but they were registered when model hasn't had relation attributes yet. When I added them I got this model:
class Person(User):
type = models.BooleanField()
avatar = models.ImageField(blank=True)
second_name = models.CharField(max_length=30, blank=True, default='')
birthday = models.DateField(blank=True, default=None)
country = models.CharField(max_length=30, blank=True, default='')
city = models.CharField(max_length=30, blank=True, default='')
school = models.CharField(max_length=60, blank=True, default='')
university = models.CharField(max_length=60, blank=True, default='')
work_place = models.CharField(max_length=60, blank=True, default='')
profession = models.CharField(max_length=60, blank=True, default='')
phone = models.CharField(max_length=30, blank=True, default='')
about = models.TextField(blank=True, default='')
latitude = models.FloatField(blank=True, default=-1)
longitude = models.FloatField(blank=True, default=-1)
friends = models.ForeignKey(
'self',
related_name='+',
)
black_list = models.ForeignKey(
'self',
related_name='+',
)
dialogues = models.ManyToManyField(
'dialogues.Dialogue',
)
news = models.OneToOneField(
'news.NewsList',
)
wall = models.OneToOneField(
'blogs.Blog',
)
But now when this model migrates I have the error: django.db.utils.IntegrityError: UNIQUE constraint failed: persons_person.wall_id.
You should change the relation with Blog model, as one Person can write more than 1 blog, hence its a 1-M relation. So in Blog model you should define a ForeignKey to Person model.
person = models.ForeignKey(
'person.Person',
related_name='walls'
)
And wall field will be removed from Person model, but from person objects you will be able to access blogs using related name walls.
If your have a necessity of having Person to Blog as 1-1 relation, then your will have to remove records from database which don't follow this constraint.

Django query for many to many relationship

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()

Categories