How to have multiple one to one relations to a specific model - django

I have a scientific info model that has a one-to-one relationship to my User model.
this is my model:
class ScientificInfo(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
**other fields**
I want to add an interviewer field to it as well so that I can chose an interviewer from the user model so I added it like this:
class ScientificInfo(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user')
interviewer = models.OneToOneField(User, on_delete=models.CASCADE, related_name='interviews')
**other fields**
but when I want to create a new user it gives me unique constraint failed error

You don't have to use OneToOneField because you're using two relations with the same table. You'd better use ForeignKey.
class ScientificInfo(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
interviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='interviews')
**other fields**

Related

It is possible to do a single complex query on these models rather than doing multiple queries?

With these models:
class User(AbstractUser):
pass
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile")
bio = models.CharField(max_length=250)
img = models.ImageField(upload_to='img_profiles/')
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post")
text = models.CharField(max_length=260)
data = models.DateTimeField(auto_now_add=True)
class Following(models.Model):
follow = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follow")
follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower")
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_that_like")
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_like")
I would need to take data from Post, User and Profile for each Post that has Post.user=Following.follow where Following.follower=request.user.id. Added to that I nedd a Sum of Like.post for each Post catched.
The first part is ok with :
qs=Following.objects.values('follow__post__id','follow__post__text',
'follow__post__data','follow__username','follow__first_name','follow__last_name',
'follow__profile__img').filter(follower_id=request.user.id).order_by('-follow__post__data')
I would like to understand if it is possible to obtain the second part with the same query or if I need a second query / subquery
I would like to understand if it is possible to obtain the second part
with the same query
It is possible with annotation.
You can import Count from django.db.models import Count
and add .annotate(like_count=Count('follow__post__post_like')) to your query

Obtaining queryset based on unrelated models

I've got the following models. I need to obtain a queryset of orders where the user's userprofile.setupstatus == 1. Is this possible or should I just add a foreign key field on the Order model to the UserProfile?
class Order(models.Model):
user = models.ForeignKey(UserCheckout, null=True, on_delete=models.CASCADE)
class UserCheckout(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
setupstatus = models.IntegerField(default=0)
It is surely possible with Django ORM
Your query should look somewhat like this
Order.objects.filter(user__user__userprofile__setupstatus=1)

Best way to filter queryset by counting number of ForeignKey in Django

I have 2 models, ChatRoom and Message:
Model ChatRoom:
class ChatRoom(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='chat_creator', null=True, blank=True)
with_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='room_user_with')
Model Message:
class Message(models.Model):
chat = models.ForeignKey(ChatRoom, on_delete=models.CASCADE, related_name='message_room')
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='message_user')
content = models.TextField()
I want to filter ChatRoom queryset by getting ChatRoom which have more than 10 messages in it.
What is the best way to do this? Thank in advance!
ChatRoom.objects.annotate(cnt=Count('message_room')).filter(cnt__gt=20)
Your related_names are misleading :); they should refer to the model containing the foreign key from the perspective of the model the foreign key refers to, e.g. chat_messages and user_messages.

Django models -> what is the best approach to access 2 separated models

i am developing a small app for sharing .
to reduce database hit i need a relationship between 2 models (Followers) and (Share)
these are my models
class Follow(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True , related_name="user_follower")
class Shared(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, models.DO_NOTHING, blank=True, null=True , related_name="user_shared")
class Profile(models.Model):
id = models.AutoField(primary_key=True)
follow = models.ManyToManyField(Follow)
user = models.OneToOneField(User, models.DO_NOTHING, blank=True,null=True , related_name="profile")
class Notes(models.Model):
id = models.AutoField(primary_key=True)
shared = models.ManyToManyField(Shared)
now i wanna do something like this in my django view
def return_users_note_shared_with(request):
followers = request.user.profile.follow.all()
return render(request , 'note.html',{ 'followers':followers})
in note.html how can i check if this note has been share with other users .
i know there is some relationship required in models but i can not
figure this out

Django inheritence question

some body please explain me the following i have two classes Userprofile and Staff.staff inherits userprofile
My Question is that if any entry has to be made to a staff table .1.It would be mandatory to fill out the details of user profile right?
Please explain this inheritence.Thanks
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
created_date = models.DateTimeField(auto_now_add=True)
emp_first_name = models.CharField(max_length=255)
emp_last_name = models.CharField(max_length=255)
gender = models.CharField(max_length=2, choices = GENDER_CHOICES, null=False)
date_of_birth = models.DateField(blank=True,null=True)
address1 = models.CharField(max_length=255)
city = models.CharField(max_length=48)
state = models.CharField(max_length=48)
country = models.CharField(max_length=48)
email_id = models.EmailField(blank=True)
class Staff(UserProfile):
role = models.ManyToManyField(Role)
designation = models.CharField(max_length=48, blank=True, null=True)
education = models.CharField(max_length=255, blank=True, null=True)
If you take a look at https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance you'll see that automatic One-to-One mappings are created. Therefore, an entry for UserProfile is saved, and an entry for Staff is saved with a OneToOne field that points to the UserProfile entry.
However, if you want Staff to just inherit all the fields, I'd recommend setting abstract = True in your UserProfile. This means that Staff inherits all those fields, but you can never create a UserProfile by itself (as described at
https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes )
class Meta:
abstract = True