Search code examples
pythonmysqldjangoapitastypie

Tastypie detail_uri_name with forignkey's attribute


I have a extended the User Django class with my own user class in django:

class MyUser(models.Model):
     user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='my_user')
     theme = models.IntegerField(default=0)
     tags = TaggableManager()

And a corresponding tastypie resource, that I want to use detail_uri_name with the username from the Django user class. Although, I do not know how.

class MyUserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['get']
        detail_uri_name = 'user_username'# ????

Error I have is: 'MyUser' object has no attribute 'user__username'

How do I access the username from MyUser as an attribute?

The line is:

 detail_uri_name = 'user_username'# ????

From the shell I can do MyUser.objects.all()[0].user.username to get the username of the associated django class.


Solution

  • You cannot use other class attribute as a detail_uri_name.

    But, in theory:

    class MyUserResource(ModelResource):
        class Meta:
            queryset = User.objects.all().select_related('user')
            allowed_methods = ['get']
            detail_uri_name = 'user__username'
    
        def get_bundle_detail_data(self, bundle):
            attrs = self._meta.detail_uri_name.split('__')
            return getattr(getattr(bundle.obj, attrs[0]), attrs[1])