Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Serialize BigIntegerField, TextField in serializer Django

I have a model which has following attributes

from django.db import models
class ApiLogs(models.Model):
    user_id = models.BigIntegerField(null=True)
    ip = models.CharField(max_length=16)
    user_agent = models.TextField(blank=True, null=True)
    client = models.CharField(max_length=50, blank=True, null=True)
    client_version = models.CharField(max_length=50, blank=True, null=True)
    token = models.TextField(blank=True, null=True)
    uri = models.CharField(max_length=200)
    method = models.CharField(max_length=20)

I have defined a serializer

from rest_framework import serializers
class ApiSerializer(serializers.Serializer):
    user_id = serializers.BigIntegerField( allow_null=True)
    ip = serializers.CharField(max_length=16)
    user_agent = serializers.TextField(allow_blank=True, allow_null=True)
    client = serializers.CharField(max_length=50, allow_blank=True, allow_null=True)
    client_version = serializers.CharField(max_length=50, allow_blank=True, allow_null=True)
    token = serializers.TextField(allow_blank=True, allow_null=True)
    uri = serializers.CharField(max_length=200)
    method = serializers.CharField(max_length=20)

But it is showing error somewhat like this

user_id = serializers.BigIntegerField( allow_null=True)
AttributeError: 'module' object has no attribute 'BigIntegerField'

for textfield

user_agent = serializers.TextField(allow_blank=True, allow_null=True)
AttributeError: 'module' object has no attribute 'TextField'

Now how to serialize this type of data.

like image 798
abhishek Avatar asked Aug 09 '16 11:08

abhishek


2 Answers

This is because the django rest framework's Serializer doesn't have a TextField. Where your model has a TextField you need to use a CharField in the serializer.

CharField A text representation. Optionally validates the text to be shorter than max_length and longer than min_length.

Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField.

The documentation isn't as clear about BigIntegerFields from models, but this line for the source code shows that IntegerField is again what you have to use in the serializer.

like image 163
e4c5 Avatar answered Oct 06 '22 08:10

e4c5


Replace TextField with CharField. Both have basically the same functionality, but serializers understand only the later.

like image 43
Arghya Bhattacharya Avatar answered Oct 06 '22 06:10

Arghya Bhattacharya