Search code examples
pythondjangotastypie

django-tastypie how to assign default value in id


tastypie i want to assign id with calling any other function in api.py class UserResource(ModelResource): class UserResource(ModelResource):

class Meta:
    collection_name="data"
    queryset = User.objects.all()
    resource_name = 'user'
    authorization = Authorization()


def dehydrate(self, bundle):
    bundle.data['user_id'] = "1"  # want to call one function here
    return bundle

but that is not working and error is

IntegrityError at /v0/user
(1048, "Column 'user_id' cannot be null")

my model code

class User(models.Model):
    user_id = models.IntegerField(primary_key=True)
    mobile_country_code = models.CharField(max_length=10L, blank=True)
    mobile_no = models.CharField(max_length=15L)
    email = models.CharField(max_length=75L, blank=True)
    email_phone = models.CharField(max_length=75L, blank=True)
    gcm_regid = models.TextField()
class Meta:
    db_table = 'users'

how to call one function for getting id form other table


Solution

  • I assume you are trying to write the user with a POST/PUT/PATCH request. Your issue is that you are using dehydrate instead of hydrate.

    Hydrate is for when you are modifying the payload that has been received from the user and will be saved.

    Dehydrate is for when you are modifying the payload that will be returned to the user.

    Because I am assuming you are trying to write the data, your dehydrate never gets called until perhaps after you have already saved your user.

    Docs for the hydrate cycle