我试图找到一种方法,我可以在Queryset中使用多个模型。例如,在我的情况下,我有2个表 - 照片和用户。
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)
我的目标是为DR_User创建一个自定义查询集,我可以从User Table(auth_user)获取userinfo,并从Photo Table中获取图像URL ...这样当我使用时 -
user = DR_user.objects.all()
我可以在我的模板中使用{{user.profile_pic}}和{{user.userinfo}}一次访问它们。
答案 0 :(得分:0)
工作太多了。
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)