Querying related model-attributes in django - python

I have the following custom user model arrangement.
```
class User(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
class StudentProfile(models.Model):
student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
location = models.CharField(max_length=8, blank=False, default='')
class TeacherProfile(models.Model):
teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
location = models.CharField(max_length=8, blank=False, default='')
gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='')
```
I am able to a query the students based on the location of their teacher (current user).
Student.objects.filter(location=request.user.teacher.location)
I can also query the user model & find all teachers/students
User.objects.filter(is_teacher=True)
QUESTION:
Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes.
[X]-This is wrong but the idea is something like;
User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork)

You can follow the OneToOneField in reverse:
User.objects.filter(teacherprofile__location='newyork')
You thus do not need to store is_teacher and is_student explicitly. You can simply filter Students with:
# Users with a related StudentProfile record
User.objects.filter(studentprofile__isnull=False)

Related

Python Django: Filtering data based on custom user model with Foreign Key

i am trying to filter a data set based on a custom user model and having some difficulty with the data.
Basically, i have a registration form in which i am making user select the company they are associated with. So i have created a custom user model with a foreign key association to the company table.
Now, i am trying to query a second dataset so when user logs in, the application looks up the users company association and filters the data to only show results that are associated to the user's company choice.
any suggestion on how i can do this?
my user model is below:
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
the table that i am trying to query on has model below:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete= models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete= models.SET_NULL, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
requestorname = models.CharField(max_length=100, null=True)
requestorage = models.CharField(max_length=2,null=True, blank=True)
child_id = models.ForeignKey(ChildID, on_delete=models.SET_NULL, null=True, blank=True)
comments = models.CharField(max_length=100,null=True, blank=True)
requestdate_create = models.DateTimeField(auto_now_add=True)
note that both table has association to customer table using a foriegn key, so i want the user to only see the order associated to the company he/she belongs to.
appreciate any directions to help write the view. Thanks
So I was able to solve my own problem. I had to pass the request in as an argument. posting it here so folks with the same question can find answer. the view goes something like this.
def externalrequest(request):
args = request.user.customer_id
external = Order.objects.filter(customer=args)
context = {'external':external}
return render(request, 'accounts/external.html', context)

Query on a model field? Is it possible in models.py? [duplicate]

This question already has an answer here:
How to query related models in django models.py
(1 answer)
Closed 3 years ago.
I have a model called StudentProfile:
class StudentProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
class_advisor = models.CharField(max_length=50)
year = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null=True)
section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True)
what I want to happen is, class_advisor to only return and accpet User with is_teacher = True.
by the way here's my User model:
class User(AbstractUser):
email = models.EmailField(
max_length=254,
unique=True,
verbose_name='Email Address',
blank=True
)
is_student = models.BooleanField(default=False, verbose_name='Student')
is_superuser = models.BooleanField(default=False, verbose_name='Administrator')
is_teacher = models.BooleanField(default=False, verbose_name='Teacher')
is_staff = models.BooleanField(default=False, verbose_name='Staff')
is_registrar = models.BooleanField(default=False, verbose_name='Registrar')
Yes, however at the moment, something is wrong with your modeling. You should make class_advisor a ForeignKey to the user model. Imagine that you store the username (or whatever unique attribute of that user) in your model. If later that teacher changes that username, then it will refer to a non-existing user, or later to a different user that picked the username.
You can set the limit_choices_to=... parameter [Django-doc]:
from django.db.models import Q
from django.contrib.auth import get_user_model
class StudentProfile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, primary_key=True, related_name='studentprofile')
class_advisor = models.ForeignKey(get_user_model(), limit_choices_to=Q(is_teacher=True), related_name='students')
year = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null=True)
section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True)
If you use forms, etc. It will limit the options to Users that are teachers, and do validation on this.
It is better to use get_user_model() [Django-doc] here to refer to your user model, since if you later alter it, the ForeignKey (and OneToOneField will refer to the new model).
Try this:
StudentProfile.objects.filter(user__is_teacher=True)
StudentProfile.objects.filter(user__is_teacher=True).values('class_advisor')

how to make USERNAME field unique for multiple type of users in User Model

I have followed these [1,2,3] links to create a custom user model by extending AbstractBaseUser class. I am storing login information of three type of users lets say teacher, Admin and students in this table. USERNAME field is emailId.
I want to make emailId unique among one type of users. In other words, in my system student can register as teacher as well with same emailId. But since emailId is USERNAME field and hence unique, I am unable to achieve this.
Please suggest how can I do this in Django application.
UserModel :
class UserModel(AbstractBaseUser):
user_type_choices = (
(constants.USER_TYPE_ADMIN, 'Admin'),
(constants.USER_TYPE_INSTITUTE, 'Institute'),
(constants.USER_TYPE_STUDENT, 'Student')
)
sys_id = models.AutoField(primary_key=True, blank=True)
name = models.CharField(max_length=127, null=False, blank=False)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
mobile = models.CharField(max_length=10, unique=True, null=False, blank=False)
user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True)
is_staff = models.BooleanField()
is_active = models.BooleanField(default=True)
objects = MyUserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ['name', 'mobile', 'user_type','is_staff']
I am using other models like StudentsDetails, TeacherDetails with foreign key to UserModel to store extra information.

Relational database - Django Rest Framework

I am trying to build relations with my database tables. Im having a tutorial lesson at the moment with 3 tables. for example (auth_user table, partyEvent table, friends table).
Now a user should be able to create just one partyEvent. Friends can join any number of partyEvent created by the users.
The owner id in the Friends model tells the partyEvent and User 'the friend' belongs to.
I am able to restrict the users to create only one partyEvent. But when i try to register friends to a partyEvent, the owner's id is not sent. Instead the default value in:
owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1')
is rather sent. Why is that happening?
models
class PartyEvent(models.Model):
name = models.CharField(max_length=100, blank=False)
location = models.CharField(max_length=100, blank=False)
owner = models.OneToOneField('auth.User', related_name = 'party', on_delete=models.CASCADE, default='1')
class Friends(models.Model):
name = models.CharField(max_length=100, blank=False)
owner = models.ForeignKey('auth.User',related_name = 'friends', on_delete=models.CASCADE, default='1')
serializers
class FriendsSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.id')
class Meta:
model = Friends
fields = ('id','name','owner')
You can set current user by assigning serializers.CurrentUserDefault() as your serializer field default. Here is an example from the doc:
owner = serializers.HiddenField(
default=serializers.CurrentUserDefault()
)

Many to Many or One to Many Django

I have the following two models in Django. One is basically an extension of the base Django user class and the other is a company model. I want to say that a user can belong to one or more companies and that a company can also have one or more contacts = "Users". Would this be a correct setup? How should I represent the tie between user and company?
User Profile model:
class Profile(models.Model):
user = models.OneToOneField(User)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
Company model:
class Company(models.Model):
name = models.CharField(max_length=120)
account_name = models.CharField(max_length=10, default="")
sales_rep = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_sales", default="")
csr = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_csr", default="")
class CompanyContact(models.Model):
name = models.CharField(max_length=40, default="")
email = models.CharField(max_length=50, default="")
user = models.ForeignKey(User)
company = models.ForeignKey(Company)
First, is there a reason to extend the User model? The default model already includes a first_name and last_name field, so you don't need an additional model just for that data. Similarly, you don't really need CompanyContact because the User model also contains email and name (again, through first_name and last_name) fields.
You can add in your contacts as a ManyToManyField. If you want to use the custom Profile model instead of User, just replace User (in the ManyToManyField) with Profile.
class Company(models.Model):
name = models.CharField(max_length=120)
account_name = models.CharField(max_length=10, default="")
sales_rep = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_sales", default="")
csr = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_csr", default="")
contacts = models.ManyToManyField(User) # or Profile
This allows each company to have many contacts and each user to be a contact of many companies – thus many-to-many.
Now, if you wanted extra data to describe the many-to-many relationship, you can have another model for that. For example, you may want to keep a record if the contact is still active or what their role is. So, you may have a CompanyContact model that is similar to:
class CompanyContact(models.Model):
active = models.BooleanField(default=False)
role = models.CharField(max_length=50, default="")
user = models.ForeignKey(User) # or Profile
company = models.ForeignKey(Company)
Then, declare the ManyToManyField relationship to use this new model:
class Company(models.Model):
...
contacts = models.ManyToManyField(User, through="CompanyContact")
# or contacts = models.ManyToManyField(Profile, through="CompanyContact")

Categories

Resources