Search code examples
djangodjango-modelstastypie

Django tastpie, how do i add/save-to two models with just once create post call


I am trying to provide a restful api from django backend to an android app using tastypie.

My sample db model is:

class Device(models.Model):
    userprofile = models.ForeignKey(UserProfile, null=True)
    device_id = models.CharField(max_length=512)
    os = models.CharField(max_length=128, null=True)
    manufacturer = models.CharField(max_length=128, null=True)
    registered_on = models.DateTimeField(default=datetime.now)

    class Meta:
        ordering = ['registered_on']
        verbose_name_plural = 'Devices'

    def __unicode__(self):
        return self.device_id


class DeviceSession(models.Model):

    device = models.ForeignKey(Device)
    device_token = models.CharField(max_length=512, blank=True)
    new_token = models.CharField(max_length=512, null=True)
    is_valid = models.BooleanField(default=True)
    issued_date = models.DateTimeField(default=datetime.now)
    expiry_date = models.DateTimeField(null=True)

and my resources.py file is :

class DeviceResource(ModelResource):
    class Meta:
        queryset = Device.objects.all()
        authorization = Authorization()
        allowed_method = ['get','post']

Now what do i do to create entries in both the models when i get a create request to the device url ie http://localhost:9999/api/v1/device/.

Im fairly new to django so would request ppl to answer with lesser complexity.


Solution

  • Tastypie offers a function you can use which is obj_create, you can use the function to create entry for DeviceSession model when Device object model is created.

    for example :

    def obj_create(self, bundle, **kwargs):
         bundle = super(DeviceResource, self).obj_create(bundle, **kwargs)
         new_object = DeviceSession() 
         new_object.device = bundle.obj
         new_object.device_token = 'what ever or data coming from post?'
         new_object.save()
         return bundle
    

    this function creates DeviceSession object when a Device object is created bundle.obj is the created object of the Device