student and establishment belong to the owner and are associated with it by foreign key. It is necessary to make sure that the student field is automatically set to establishmetn for communication through the user.
Establishment.models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from user.models import CustomUser
class Establishment(models.Model):
owner = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
region = models.CharField(max_length=255)
name = models.CharField(max_length=255)
adrees = models.CharField(max_length=255)
contact_phone = PhoneNumberField(null=False, blank=False, unique=True)
contact_email = models.EmailField(max_length=254)
objects = models.Manager()
class Section(models.TextChoices):
boxing = 'Бокс', 'Бокс'
swimming = 'Плавание', 'Плавание'
weightlifting = 'Тяжелая атлетика', 'Тяжелая атлетика'
athletics = 'Легкая атлетика', 'Легкая атлетика'
wrestling = 'Борьба', 'Борьба'
greco_roman_wrestling = 'Греко-римская борьба', 'Греко-римская борьба'
def __str__(self) -> str:
return self.name
Student.models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from establishment.models import Establishment
from user.models import CustomUser
class Student(models.Model):
owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
lastname = models.CharField(max_length=255)
name = models.CharField(max_length=255)
fathername = models.CharField(max_length=255)
contact_phone = PhoneNumberField(null=False, blank=False, unique=True)
contact_email = models.EmailField(max_length=254)
iin = models.IntegerField(null=False, unique=True)
photo = models.ImageField()
section = models.CharField(choices=Establishment.Section.choices, max_length=255)
study_place = models.ForeignKey(Establishment, on_delete = models.CASCADE) # Надо сделать автопостановку учреждения опираясь на id пользователя из запроса
objects = models.Manager()
student_mng = StudentManager()
def __str__(self) -> str:
return self.name
Student.serializers.py
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
study_place = Establishment.objects.filter(owner_id=1)
class Meta:
model = Student
fields = '__all__'
I tried doing this through the serializer by study_place = Establishment.objects.filter(owner_id=1) and everything works as it should, but the owner_id must be dynamic and set to the value of the authorized user who is making the request