Hi,
I have two models (Patients and PatientAddress). I want to create a new patient using POST method and data should be inserted in Patient and PatientAddress tables. But the data is inserted only into Patients table and not in PatientAddress table.
When I POST a new patient with Address then automatically it should create a new record in PatientAddress table with patnt_refno referencing to the Patient table. Could someone please assist to proceed further.
Below is my code.
POST Input:
{
"Address": [
{
"line": "3A insert Second Street",
"city": "insert city",
"country": "India"
}
],
"patnt_id": "P14",
"surname": "Smith",
"forename": "James",
"gender": "M",
"active": 1
}
models.py
class Patients(models.Model):
patnt_refno = models.AutoField(primary_key=True)
patnt_id = models.CharField(unique=True, max_length=10, blank=True, null=True)
surname = models.CharField(max_length=30, blank=True, null=True)
forename = models.CharField(max_length=50, blank=True, null=True)
gender = models.CharField(max_length=1, blank=True, null=True)
dttm_of_birth = models.DateTimeField(blank=True, null=True)
dttm_of_death = models.DateTimeField(blank=True, null=True)
marital_status = models.CharField(max_length=50, blank=True, null=True)
active = models.IntegerField()
def __str__(self):
return self.patnt_id
class Meta:
managed = False
db_table = 'patients'
class PatientAddress(models.Model):
addss_refno = models.AutoField(primary_key=True)
patnt_refno = models.ForeignKey('Patients', db_column='patnt_refno', related_name='Address')
line = models.CharField(max_length=30, blank=True, null=True)
city = models.CharField(max_length=50, blank=True, null=True)
state = models.CharField(max_length=50, blank=True, null=True)
country = models.CharField(max_length=50, blank=True, null=True)
postcode = models.CharField(max_length=50, blank=True, null=True)
active = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'patientaddress'
serializers.py
class PatientAddressSerializer(serializers.ModelSerializer):
class Meta:
model = PatientAddress
fields = ('line','city','country')
class PatientsSerializer(serializers.ModelSerializer):
Address = PatientAddressSerializer(read_only=True,many=True)
class Meta:
model = Patients
fields = ('Address','patnt_refno','patnt_id','surname','forename','gender','active')
views.py
class PatientsList(APIView):
def get(self, request):
patients = Patients.objects.filter(gender='M',active=1).order_by('dttm_of_birth').reverse()
serializer = PatientsSerializer(patients, many=True)
return Response(serializer.data)
def post(self, request):
serializer = PatientsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^patients/$', views.PatientsList.as_view()),
]
Thanks in advance,
Thiagu Palaniappan