Я новичок в Django Rest Framework. Я использовал обычный Django, я хочу что-то похожее на CreateView Django для этой модели.
Введение: суперпользователь - единственный пользователь. Все пациенты принадлежат пользователю, а эмбрионы принадлежат пациенту. Один пациент может иметь несколько эмбрионов. Ниже представлены мои модели
class Patients(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=35)
email = models.EmailField(unique=True)
class Embryo(models.Model):
patient = models.ForeignKey(Patients, on_delete=models.CASCADE)
code_name = models.CharField(max_length=100)
karyotype = models.CharField(max_length=100)
GENDER_CHOICES = (
("M", "Male"),
("F", "Female"),
)
sex = models.CharField(max_length=1, choices=GENDER_CHOICES)
Я пытаюсь создать представления для моих моделей.
Ниже то, что я имею до сих пор
class PatientsApiView(viewsets.ModelViewSet):
"""Handles Creating, reading and updating Patients"""
serializer_class = serializers.PatientsSerializer
queryset = Patients.objects.all()
authentication_classes = (TokenAuthentication,)
filter_backends = (filters.SearchFilter,)
search_fields = ("first_name", "last_name", "phone", "email",)
def form_valid(self, form, *args, **kwargs):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
"""How can I get the above with Django Rest Framework. Can I do:
def __getattr__(self, user):
return self.request.user
"""
Ниже представлен набор настроек для EmbroApiView
class EmbroApiView(viewsets.ModelViewSet):
"""Handles Creating, reading and updating Patients"""
serializer_class = serializers.EmbryoSerializer
queryset = Embryo.objects.all()
authentication_classes = (TokenAuthentication,)
filter_backends = (filters.SearchFilter,)
search_fields = ("code_name", "karyotype", "sex", "down_syndrome",)
def form_valid(self, form, *args, **kwargs):
self.object = form.save(commit=False)
pk = self.kwargs.get('pk')
self.object.patient = get_object_or_404(Patient, pk=pk)
self.object.save()
return super().form_valid(form)
"""How can I get the above with Django Rest Framework. Can I do:
def __getattr__(self, patient):
return get_object_or_404(Patients, pk=self.patient.pk)
"""
Согласно решению @Daniel Roseman. Правильно ли я это сделал?
class PatientsApiView(viewsets.ModelViewSet):
"""Handles Creating, reading and updating Patients"""
serializer_class = serializers.PatientsSerializer
queryset = Patients.objects.all()
authentication_classes = (TokenAuthentication,)
filter_backends = (filters.SearchFilter,)
permission_classes = (IsAuthenticated,)
search_fields = ("first_name", "last_name", "phone", "email",)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class EmbroApiView(viewsets.ModelViewSet):
"""Handles Creating, reading and updating Patients"""
serializer_class = serializers.EmbryoSerializer
queryset = Embryo.objects.all()
authentication_classes = (TokenAuthentication,)
filter_backends = (filters.SearchFilter,)
permission_classes = (IsAuthenticated,)
search_fields = ("code_name", "karyotype", "sex", "down_syndrome",)
def perform_create(self, serializer):
serializer.save(patient_id=self.kwargs['pk'])