.save() method returning an saved instance of object but object creation does not take place in DB

23 views
Skip to first unread message

Sarthak Adhikari

unread,
May 21, 2019, 11:57:06 AM5/21/19
to Django REST framework
THE PROBLEM

Whenever I send data through post, the data gets validated, I get an output with save() method(I get a PK implying that the object was saved?) but the creation does not take place in the DB.

 I tried running UsrInDys.objects.create() from the shell and everything seemed to work fine from the shell. Just not from the django rest serializer method.

 I turned on my PyCharm Debugger and went deep into the .save() serializer method. It essentially did the same thing, Model.objects.create(**validated_data) and got an object(which implies the change to DB did take place, right?). I get the same kind of output when I try to create an object from the shell. But the object creation also takes place in the DB when I do it from the shell. 

System Details:
> PostgreSQL version 11.0
> Python 3.5
> Django 2.2.1
> Django-restframework 3.8.2
> Linux Mint 18.3

#INSIDE APIVIEW CLASS

def post(self, request):
    usr_in_dys_serializer = UserInDysSerializer(data=request.data)
    if usr_in_dys_serializer.is_valid():
        saved_usr_in_dys = usr_in_dys_serializer.save(no_of_days=no_of_days) # Output: UsrInDys object (2068) <---- but not being saved to the Database....

#INSIDE SERIALIZER.PY

class UserInDysSerializer(serializers.ModelSerializer):

    class Meta:
        model = UsrInDys
        strt_day = serializers.DateField()
        end_day = serializers.DateField()
        fields = ('strt_day', 'end_day', 'no_of_days')
        extra_kwargs = {
             'no_of_days': {'read_only': True}
        }


#INSIDE MODEL.PY

class UsrInDys(models.Model):
    trip_id = models.AutoField(primary_key=True)
    strt_day = models.DateField()
    end_day = models.DateField()
    no_of_days = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'usr_in_dys'

    def __unicode__(self):
        return [self.strt_day, self.end_day]

#INSIDE SETTTINGS.PY

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': env("USER"),
        'PASSWORD': env("PASSWORD"),
        'HOST': env("HOST"),
        'PORT': '5433',
    }
}

DATABASES['default']['ATOMIC_REQUESTS'] = True

Carl Nobile

unread,
May 27, 2019, 8:35:51 PM5/27/19
to Django REST framework
I can see a few issues here.
  1. You defined 'strt_day' and 'end_day' inside the Meta class, you cannot do this. It won't work correctly.
  2. If you actually get back a real PK from the DB then the DB at least thinks it got created.
Are you sure it didn't fail for some other reason?

To be honest, the scenario you propose is kind of impossible, so I don't know what else to suggest.

~Carl

Reply all
Reply to author
Forward
0 new messages