Upload Document in Django Rest Framework Dynamic Form - django

In my Djago-React Application I am creating a form which has dynamic fields as well as an option to upload the document
For that I am using multipart/form-data and its working fine when I am using it only to upload the document but as soon as I enter the data in dynamic fields the serializer stops handling the data.
Example data:
Form Data:
transaction_no: 2341
document: (binary)
items[0][product]: 5
items[0][quantity]: 1
items[0][fault]: Repairable
items[1][product]: 4
items[1][quantity]: 2
items[1][fault]: Return
allotment: 122
Response:
{"items":[{"product":["This field is required."]},{"product":["This field is required."]}]}
Serializer:
class DeliveredItemsSerializer(serializers.ModelSerializer):
class Meta:
model = DeliveredItems
fields = "__all__"
class DeliveredSerializer(serializers.ModelSerializer):
items = DeliveredItemsSerializer(many=True,required=False)
class Meta:
model = Delivered
fields = "__all__"
def create(self, validated_data):
items_objects = validated_data.pop('items', None)
prdcts = []
try:
for item in items_objects:
i = DeliveredItems.objects.create(**item)
prdcts.append(i)
instance = Delivered.objects.create(**validated_data)
print("prdcts", prdcts)
instance.items.set(prdcts)
return instance
except:
instance = Delivered.objects.create(**validated_data)
return instance
def update(self, instance, validated_data):
items_objects = validated_data.pop('items',None)
prdcts = []
try:
for item in items_objects:
print("item", item)
fk_instance, created = DeliveredItems.objects.update_or_create(pk=item.get('id'), defaults=item)
prdcts.append(fk_instance.pk)
instance.items.set(prdcts)
instance = super(DeliveredSerializer, self).update(instance, validated_data)
return instance
except:
instance = super(DeliveredSerializer, self).update(instance, validated_data)
return instance
Models:
class DeliveredItems(models.Model):
choices = (('Repairable', 'Repairable'),('Return', 'Return'), ('Damage', 'Damage'), ('Swap Return', 'Swap Return'))
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=0)
fault = models.CharField(max_length=100, default="Repairable", choices=choices)
class Delivered(models.Model):
allotment = models.ForeignKey(Allotment, on_delete=models.CASCADE)
delivered = models.BooleanField(default=False)
items = models.ManyToManyField(DeliveredItems)
document = models.FileField(upload_to='delivered/', null=True, blank=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
How can I handle the dynamic data that don't come in a list and comes as something like this items[0][product]: 5?
I need the data to be in this format:
{
"transaction_no": 2335,
"delivered": false,
"document": {
"uid": "rc-upload-1599739825759-7"
},
"items": [
{
"product": 4,
"quantity": "12",
"fault": "Repairable"
},
{
"product": 5,
"quantity": "1",
"fault": "Return"
}
],
"allotment": 116
}

please try this one if you want to handle form data in DRF
in view, please inherit viewsets.ModelViewSet
def dict_shallow_copy(d):
return dict(d.items())
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs.get("data", {})
if isinstance(data, dict):
data = dict_shallow_copy(data)
//get your data here, sameple like this
data['items'] = self.kwargs
data['transaction_no'] = self.kwargs
kwargs['data'] = data
else:
raise ValidationError("Invalid data type")
return super().get_serializer(*args, **kwargs)

Related

Need to add one model fields in the another model serializers but throwing error while POST the request

models.py
class Product(models.Model):
product_id = models.AutoField(unique=True, primary_key=True)
product_name = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = "product_master"
def __str__(self):
return self.product_name
class Organisation(models.Model):
"""
Organisation model
"""
org_id = models.AutoField(unique=True, primary_key=True)
org_name = models.CharField(max_length=100)
org_code = models.CharField(max_length=20)
org_mail_id = models.EmailField(max_length=100)
org_phone_number = models.CharField(max_length=20)
org_address = models.JSONField(max_length=500, null=True)
product = models.ManyToManyField(Product, related_name='products')
org_logo = models.ImageField(upload_to='org_logo/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
db_table = "organisation_master"
def __str__(self):
return self.org_name
serializers.py
class Product_Serializers(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('product_id', 'product_name',)
class Organisation_Serializers(serializers.ModelSerializer):
product = Product_Serializers(many=True)
class Meta:
model = Organisation
fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product')
depth = 1
"
While i tried to do POST method for the organisation model I have tried giving the input for product as "product: 5" and "product: {"product_id": 5,"product_name": "time"} in the postman form data but it is showing as
{
"status": "error",
"code": 400,
"data": {
"product": [
"This field is required."
]
},
"message": "success"
}
Views.py
class Organisation_Viewset(DestroyWithPayloadMixin,viewsets.ModelViewSet):
renderer_classes = (CustomRenderer, ) #ModelViewSet Provides the list, create, retrieve, update, destroy actions.
queryset=models.Organisation.objects.all()
parser_classes = [MultiPartParser, FormParser]
serializer_class=serializers.Organisation_Serializers
def create(self, request, *args, **kwargs):
data = request.data
new_organisation= models.Organisation.objects.create(org_name=data["org_name"],org_code = ["org_code"], org_mail_id =data["org_mail_id"],org_phone_number= data["org_phone_number"], org_address=data["org_address"],org_logo = data["org_logo"])
new_organisation.save()
for product in data["product"]:
product_id = models.Product.objects.get(product_id=product["product_id"])
new_organisation.products.add(product_id)
serializer = serializers.Organisation_serializers(new_organisation)
return Response(serializer.data)
I need to post like this product: {"product_id": 5,"product_name": "time"}, what fields are available in the product model it should be posted on this product field.
Can you please suggest me a way as i tried many ways as per my knowledge but it dosen't worked.
you are using a tuple for fields, put a comma behind product in youre fields. If you use a list then dont use an end comma
fields = ('org_id', 'org_name', 'org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product',)
depth = 1
Update your serializers to:
class Product_Serializers(serializers.Serializer):
product_id = serializers.IntegerField()
product_name = serializers.CharField(max_length=100)
class Organisation_Serializers(serializers.ModelSerializer):
product = Product_Serializers(many=True)
class Meta:
model = Organisation
fields = (
'org_id',
'org_name',
'org_address',
'org_phone_number',
'org_mail_id',
'org_logo',
'org_code',
'product'
)
depth = 1
Update your views as:
class Organisation_Viewset(ModelViewSet):
# ModelViewSet Provides the list, create, retrieve, update, destroy actions.
renderer_classes = (CustomRenderer,)
queryset = Organisation.objects.all()
parser_classes = [MultiPartParser, FormParser, JSONParser]
serializer_class = Organisation_Serializers
def create(self, request, *args, **kwargs):
serializer = Organisation_Serializers(data=request.data)
serializer.is_valid(raise_exception=True)
product_data = serializer.validated_data.pop('product')
does_not_exist = []
product_instances = []
for product in product_data:
try:
product_instance = Product.objects.get(
product_id=product['product_id'],
product_name=product['product_name']
)
product_instances.append(product_instance)
except Product.DoesNotExist:
does_not_exist.append(product)
if len(does_not_exist) > 0:
return Response({
'error': 'Product does not exist',
'does_not_exist': does_not_exist
}, status=400)
organization = Organisation.objects.create(**serializer.validated_data)
for product in product_instances:
organization.product.add(product)
organization.save()
return Response(Organisation_Serializers(organization).data, status=201)
Now we can send the list of product objects for the create API:
curl --location --request POST 'http://localhost:8000/api/organization/' \
--header 'Content-Type: application/json' \
--data-raw '{
"org_id": "12345",
"org_name": "test organization",
"org_address": "test",
"org_phone_number": "12345",
"org_mail_id": "test#te.st",
"org_code": "12345",
"product": [
{
"product_id": 1,
"product_name": "test p1"
},
{
"product_id": 2,
"product_name": "test p2"
}
]
}'

How to save a nested object in a post request correctly?

I am trying to work with a post request were I am first saving a Tag object, which then becomes the tag field of a Tagging object. However, no matter what combinations I have tried, despite the Tag Post method working, when I pass a json object like this:
{
"user_id": 1,
"gameround_id": 2015594866,
"resource_id": 2975,
"tag": {
"name": "TESTTAGGGG2222",
"language": "en"
},
"score": 0,
"origin": ""
}
I keep getting this message:
{
"name": [
"This field is required."
],
"language": [
"This field is required."
]
}
However, when I pass a Tag, it works.
This is the post method:
def post(self, request, *args, **kwargs):
if not isinstance(request.user, CustomUser):
current_user_id = 1
else:
current_user_id = request.user.pk
gameround = request.data.get('gameround', '')
random_resource = request.data.get('resource', '')
created = datetime.now()
score = 0
origin = ''
name = request.data.get('name', '')
language = request.data.get('language', '')
tag_serializer = TagSerializer(data=request.data)
tagging_serializer = TaggingSerializer(data=request.data)
if tag_serializer.is_valid(raise_exception=True):
tag_serializer.save(tag=request.data)
if tagging_serializer.is_valid(raise_exception=True):
tagging_serializer.save(tagging=request.data, tag=tag_serializer.data)
return Response({"status": "success", "data": tagging_serializer.data},
status=status.HTTP_201_CREATED)
# else:
# return Response({"status": "success", "data": tag_serializer.data},status=status.HTTP_201_CREATED)
else:
return Response({"status": "error", "data": tag_serializer.errors},
status=status.HTTP_400_BAD_REQUEST)
How do I correctly pass the nested object in the post method so that I don't get this error anymore?
models.py
class Tag(models.Model):
name = models.CharField(max_length=256)
language = models.CharField(max_length=256)
objects = models.Manager()
def __str__(self):
return self.name or ''
#property
def tags(self):
tags = self.tagging.values('tag')
return tags.values('tag_id', 'tag__name', 'tag__language')
class Tagging(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
gameround = models.ForeignKey(Gameround, on_delete=models.CASCADE, related_name='taggings')
resource = models.ForeignKey(Resource, on_delete=models.CASCADE, related_name='taggings')
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name='tagging')
created = models.DateTimeField(editable=False, null=True)
score = models.PositiveIntegerField(default=0)
# media_type = models.ForeignKey(Gamemode, on_delete=models.CASCADE)
origin = models.URLField(max_length=256, blank=True, default='')
objects = models.Manager()
def __str__(self):
return str(self.tag) or ''
serializers.py
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('name', 'language')
def create(self, validated_data):
tag_data = validated_data.pop('tag')
Tag.objects.create(**tag_data)
return tag_data
def to_representation(self, data):
data = super().to_representation(data)
return data
class TaggingSerializer(serializers.ModelSerializer):
tag = TagSerializer(required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Tagging
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag', 'created', 'score', 'origin')
depth = 1
def create(self, validated_data):
"""Create and return a new tagging"""
tag_data = validated_data.pop('tag', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag'] = tag
tagging = Tagging(
user=validated_data.get("user"),
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
tag=validated_data.get("tag"),
created=datetime.now(),
score=validated_data.get("score"),
origin=validated_data.get("origin")
)
tagging.save()
return tagging
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag'] = TagSerializer(instance.tag).data
return rep
In your post method, you made
tag_serializer = TagSerializer(data=request.data)
if tag_serializer.is_valid(raise_exception=True):
# the rest of the code
this means that your data will pass to TagSerializer so DRF will check if the fields for this serializer are in the request body or not, and it's not provided, cause this data does not belong to this serializer, it belongs to TaggingSerializer so this will give you an error This field is required
So, you need to send your request data only to TaggingSerializer, try that and let's see what will happen, and I will suggest using serializers.Serializer instead of using serializers.ModelSerializer for better performance

How do I get my serializer to return data from a dependent field in my model?

I'm using Django 2 and Python 3.7. I have these models set up. One (Coop) is dependent on the other (CoopType) using Many-To-Many ...
class CoopTypeManager(models.Manager):
def get_by_natural_key(self, name):
return self.get_or_create(name=name)[0]
class CoopType(models.Model):
name = models.CharField(max_length=200, null=False, unique=True)
objects = CoopTypeManager()
class CoopManager(models.Manager):
# Look up by coop type
def get_by_type(self, type):
qset = Coop.objects.filter(type__name=type,
enabled=True)
return qset
# Look up coops by a partial name (case insensitive)
def find_by_name(self, partial_name):
queryset = Coop.objects.filter(name__icontains=partial_name, enabled=True)
print(queryset.query)
return queryset
# Meant to look up coops case-insensitively by part of a type
def contains_type(self, types_arr):
filter = Q(
*[('type__name__icontains', type) for type in types_arr],
_connector=Q.OR
)
queryset = Coop.objects.filter(filter,
enabled=True)
return queryset
class Coop(models.Model):
objects = CoopManager()
name = models.CharField(max_length=250, null=False)
types = models.ManyToManyField(CoopType)
address = AddressField(on_delete=models.CASCADE)
enabled = models.BooleanField(default=True, null=False)
phone = PhoneNumberField(null=True)
email = models.EmailField(null=True)
web_site = models.TextField()
I have the following serializers set up, designed to return the data in JSON form ...
class CoopTypeField(serializers.PrimaryKeyRelatedField):
queryset = CoopType.objects
def to_internal_value(self, data):
if type(data) == dict:
cooptype, created = CoopType.objects.get_or_create(**data)
# Replace the dict with the ID of the newly obtained object
data = cooptype.pk
return super().to_internal_value(data)
...
class CoopTypeSerializer(serializers.ModelSerializer):
class Meta:
model = CoopType
fields = ['id', 'name']
def create(self, validated_data):
"""
Create and return a new `CoopType` instance, given the validated data.
"""
return CoopType.objects.create(**validated_data)
def update(self, instance, validated_data):
"""
Update and return an existing `CoopType` instance, given the validated data.
"""
instance.name = validated_data.get('name', instance.name)
instance.save()
return instance
class CoopSerializer(serializers.ModelSerializer):
types = CoopTypeSerializer(many=True)
address = AddressTypeField()
class Meta:
model = Coop
fields = ['id', 'name', 'types', 'address', 'phone', 'enabled', 'email', 'web_site']
extra_kwargs = {
'phone': {
'required': False,
'allow_blank': True
}
}
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['types'] = CoopTypeSerializer(instance.types).data
rep['address'] = AddressSerializer(instance.address).data
return rep
def create(self, validated_data):
#"""
#Create and return a new `Snippet` instance, given the validated data.
coop_types = validated_data.pop('types', {})
instance = super().create(validated_data)
for item in coop_types:
coop_type, _ = CoopType.objects.get_or_create(name=item['name']) #**item)
instance.types.add(coop_type)
return instance
However, the dependent field, "type" is always returned as "null," despite the fact that I can see there is valid data in the database. Here is what happens when I run my curl request
curl -v --header "Content-type: application/json" --request GET "http://127.0.0.1:8000/coops/?contains=resource"
[{"id":348,"name":"Garden Resources of Woodlawn (GRoW)","types":{"name":null}
How do I edit my serializer such that it returns the values of the dependent type?
Try to remove rep['types'] = CoopTypeSerializer(instance.types).data from to_representation(...) method,
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['types'] = CoopTypeSerializer(instance.types).data
rep['address'] = AddressSerializer(instance.address).data
return rep
OR
use instance.types.all() instead of instance.types, because, here the instance.types is a Manager method, which doesn't return any QuerySet
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['types'] = CoopTypeSerializer(instance.types.all(), many=True).data
rep['address'] = AddressSerializer(instance.address).data
return rep

DRF - Format Serializer's output from QuerySet

I am working with Django Rest Framework by firt time and now I'm trying to get an output like this:
{
"qty": 5,
"total": 20,
"items": [
{
"id": 1,
"name": "name_1"
},
{
"id": 2,
"name": "name_2"
}
]
}
from a Serializer. The result data in output above, came from a queryset. I'd like to work with the queryset inside the serializer class. I've not been able to get results as I want without makeing queries inside the serializer:
class ResSerializer(serializers.Serializer):
qty = serializers.SerializerMethodField()
items = serializers.SerializerMethodField()
total = serializers.SerializerMethodField()
def get_qty(self, obj):
try:
return Model.objects.filter(...)\
.aggregate(qty=Sum('job__long'))\
.get('qty')
except KeyError:
return 0
def get_items(self, obj):
print 'testing'
def get_total(self, obj):
return 0
class Meta:
fields = ('qty', 'items', 'total')
I'm calling Serializer like this:
queryset = Model.objects.filter(...)
serialized = ResSerializer(queryset, many=False, context={'current_user': request.user})
But this is not working as I want. Any sugestion? Thanks.
UPDATE
This is the model I query to:
class Intermediate(models.Model):
partner = models.ForeignKey('partner.Partner')
job = models.ForeignKey(Job)
joined_at = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
status = models.SmallIntegerField(default=STATUS_ACCEPTED)
reason_index = models.SmallIntegerField('Cancel reason', default=REASON_3)
start_time = models.TimeField(null=True)
end_time = models.TimeField(null=True)
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
And here's the view:
class ResView(CustomAPIView):
authentication_classes = (CustomTokenAuthentication, )
# permission_classes = (PartnerAuthenticatedOnly, ) # Uncomment this on server
def post(self, request, *args, **kwargs):
try:
queryset = JobPartner.objects.filter(...)
serialized = ResSerializer(queryset, many=False, context={'current_user': request.user})
response_success_object(self.response_dic, serialized.data)
return Response(self.response_dic)
except Exception, e:
print e
To get the items representation, you can use ItemsSerializer which will give the serialized data having id and name.
class ItemsSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel # specify your model
fields = ('id', 'name') # return these 2 fields in the representation
This serializer when dealing with multiple instances will return the serialized data in below fashion.
[
{
"id": 1,
"name": "name_1"
},
{
"id": 2,
"name": "name_2"
}
]
Now, the qty and total fields depends on the queryset and not a particular object of the queryset, it would be better if you compute them separately in your view. Then create a dictionary containing the fields items, qty and total and return it as the response.
class ResView(CustomAPIView):
authentication_classes = (CustomTokenAuthentication, )
# permission_classes = (PartnerAuthenticatedOnly, ) # Uncomment this on server
def post(self, request, *args, **kwargs):
try:
queryset = JobPartner.objects.filter(...)
qty = self.get_qty() # compute the value of qty
total = self.get_total() # compute the value of total
items_serializer = ItemsSerializer(queryset, many=True)
items = items_serializer.data # compute the value of items
return_dict = { # prepare response data
'qty' : qty,
'total': total,
'items': items
}
return Response(return_dict) # return the response
except Exception, e:
print e

"This field is required." when sending JSON using POST with Django REST Framework

I have the following JSON I'm trying to post:
[
{
"action_alert_details": [],
"action_email": [
{
"tskmail_attach": null,
"tskmail_id": 4444,
"tskmail_memo": "TEST!",
"tskmail_priority": 1,
"tskmail_subject": "TEST!",
"tskmail_to_ext": "blah#blah.com",
"tskmail_to_int": null
}
],
"action_job_details": [],
"action_log_details": [],
"action_snmp_details": [],
"action_variable_details": [],
"nodmst_name": null,
"owner_name": "Operations ",
"servicemst_name": null,
"tskmst_desc": null,
"tskmst_id": 4444,
"tskmst_lstchgtm": "2014-09-17T16:02:29",
"tskmst_name": "act_test ",
"tskmst_public": "Y",
"tskmst_type": 1
}
]
When sending it through the following view, it's complaining:
[
{
"action_email": [
{
"tskmail_id": "This field is required."
}
]
}
]
But as you can see in my JSON at the top, it's there. So, why does my view not seem to recognize that it's there during serialization?
def put(self, request, format=None):
data = request.DATA
owner = data[0]['owner_name']
ownerid = Owner.objects.filter(owner_name=owner).values_list('owner_id', flat=True)[0]
data[0].update({'owner_id': ownerid})
actid = data[0]['tskmst_id']
actname = data[0]['tskmst_name']
if data[0]['nodmst_name'] == None:
data[0].update({'nodmst_id': None})
else:
nodname = data[0]['nodmst_name']
nodid = Nodmst.objects.filter(nodmst_name=nodname).values_list('nodmst_id', flat=True)[0]
data[0].update({'nodmst_id': nodid})
if data[0]['servicemst_name'] == None:
data[0].update({'servicemst_id': None})
else:
servicename = data[0]['servicemst_name']
serviceid = Servicemst.objects.filter(servicemst_name=servicename).values_list('servicemst_id', flat=True)[0]
data[0].update({'servicemst_id': serviceid})
if Tskmst.objects.filter(tskmst_name=actname).exists():
data[0]['tskmst_id'] = Tskmst.objects.filter(tskmst_name=actname).values_list('tskmst_id', flat=True)[0]
data[0]['action_email'][0]['tskmail_id'] = Tskmst.objects.filter(tskmst_name=actname).values_list('tskmst_id', flat=True)[0]
else:
maxtskid = Tskmst.objects.latest('tskmst_id').tskmst_id
data[0]['tskmst_id'] = maxtskid + 1
data[0]['action_email'][0]['tskmail_id'] = maxtskid + 1
Tblcnt.objects.filter(tblcnt_tblname='tskmst').update(tblcnt_lstid=(maxtskid +1))
Tblcnt.objects.filter(tblcnt_tblname='tskmail').update(tblcnt_lstid=(maxtskid +1))
serializer = self.get_serializer_class()(data=request.DATA, many=True)
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)
Here is my serializers that are pulling the data together:
class ActionMailSerializer(serializers.ModelSerializer):
class Meta:
model = Tskmail
resource_name = 'tskmail'
class ActionPUTSerializer(serializers.ModelSerializer):
owner_id = serializers.Field(source='owner_id')
action_email = ActionMailSerializer()
class Meta:
model = Tskmst
resource_name = 'tskmst'
depth = 1
fields = ('tskmst_id', 'tskmst_name', 'tskmst_desc', 'tskmst_type', 'owner_id', 'tskmst_public',
'tskmst_lstchgtm', 'nodmst_id', 'servicemst_id', 'action_email', 'action_alert_details',
'action_snmp_details', 'action_job_details', 'action_log_details', 'action_variable_details')
Posting this for the potential that other people might experience this issue which seems to be pertaining to it being a legacy DB. The problem lies in the fact that the PK field in "tskmail" table is also a FK to "tskmst".
See Multi-Column Primary Key support for more info.
What I ended up doing is making another set of models strictly for PUT that has no FK relationship but is strictly an Integer Field.
class TskmailPOST(models.Model):
tskmail_id = models.IntegerField(primary_key=True)
tskmail_to_int = models.TextField(blank=True)
tskmail_to_ext = models.TextField(blank=True)
tskmail_subject = models.TextField(blank=True)
tskmail_memo = models.TextField(blank=True) # This field type is a guess.
tskmail_priority = models.SmallIntegerField(blank=True, null=True)
tskmail_attach = models.TextField(blank=True)
class Meta:
managed = False
db_table = 'tskmail'
Instead of -
class TskmailPOST(models.Model):
tskmail_id = models.ForeignKey(Tskmst, db_column='tskmail_id', primary_key=True)
tskmail_to_int = models.TextField(blank=True)
tskmail_to_ext = models.TextField(blank=True)
tskmail_subject = models.TextField(blank=True)
tskmail_memo = models.TextField(blank=True) # This field type is a guess.
tskmail_priority = models.SmallIntegerField(blank=True, null=True)
tskmail_attach = models.TextField(blank=True)
class Meta:
managed = False
db_table = 'tskmail'
Then I had to call 2 separate serializers and using the POST data, break it into 2 separate dict files and validate the first, load it then validate the second and load it.