Custom Querysets using Multiple Models in Django -
i trying findout way in can use multiple models in queryset. instance, in case have 2 tables - photo , user.
class photo(models.model): username = models.foreignkey(user) image = models.imagefield(upload_to='photos') alt_text = models.charfield(max_length=255) class dr_user(models.model): userid = models.foreignkey(user) follows = models.manytomanyfield('self', related_name='followed_by', symmetrical=false, blank=true) objects = dr_user_manager() class dr_user_query_set(queryset): def profile_pic(self): # uid = self.userid photo = photo.objects.get(username=uid) if photo.exists(): return photo.image.url else: return 'http://d12df125d01b8a258a3a-8112fdc02f7d385b44f56eb9e899d81c.r88.cf2.rackcdn.com/default.png' def userinfo(self): uid = self.userid obj = user.objects.get(id=uid) userinfo = obj.first_name + ' ' + obj.last_name return userinfo.title() class dr_user_manager(models.manager): def get_query_set(self): return dr_user_query_set(self.model) def __getattr__(self, name): return getattr(self.get_query_set(), name)
my aim create custom queryset dr_user can userinfo user table(auth_user) , image url photo table...so when use -
user = dr_user.objects.all()
i can access them @ once using {{ user.profile_pic }} , {{ user.userinfo }} in template.
too work.
class dr_user(models.model): ... @property def profile_pic(self): try: return self.userid.image.url except models.doesnotexist: return settings.default_profile_pic_url @property def userinfo(self): return unicode(self.userid)
Comments
Post a Comment