django - 从不同的模型字段名获取一组对象 [英] django - Get a set of objects from different models field names

查看:394
本文介绍了django - 从不同的模型字段名获取一组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看看我的模型。

  class BackgroundImage(models.Model):
user = models .ForeignKey(User)
image = models.ImageField(upload_to = get_upload_file_name)
caption = models.CharField(max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

class ProfilePicture(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to = get_upload_file_name)
caption = models.CharField (max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

class Album(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

class Meta:
ordering = ['-pub_date ']
verbose_name_plural =('Albums')

def __unicode __(self):
return self.name

class Photo(models.Mo del):
user = models.ForeignKey(User)
album = models.ForeignKey(Album,default = 3)
image = models.ImageField(upload_to = get_upload_file_name)
caption = models.CharField(max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

如何获取照片的所有图像 ProfilePicture BackgroundImage 从他们的图像字段在一个集合。然后通过 -pub_date 过滤它们以显示在模板中?请帮我出来会非常感激!谢谢。



修改



注意:我需要 ProfilePicture BackgroundImage 可以使用 UserProfile 这样:

$来自django.db导入模型的
$ b $ $ $ $
从django.contrib.auth.models导入用户
从profile_picture.models导入ProfilePicture
from background_image.models import BackgroundImage

class UserProfile(models.Model):
user = models.OneToOneField(User)
permanent_address = models.TextField()
temporary_address = models.TextField()
profile_pic = models.ForeignKey(ProfilePicture)
background_pic = models.ForeignKey(BackgroundImage)

def __unicode __(self):
return self.user.username

User.profile = property(lambda u:UserProfile.objects.get_or_create(user = u)[0])
/ pre>

解决方案

有一个 InheritanceManager 提供d作为 django-model-utils 的一部分,它允许您这样做,请参阅 docs



要在Linux / Mac中安装:

  sudo pip install django-model-utils 



令人吃惊的是,在Windows上使用 easy_install pip 进行安装不太直接,请参阅:如何在Windows上安装Python软件包。一个快速而肮脏的方法是从 django-model-util / 目录/ srcrel =nofollow noreferrer>这里进入django项目的顶级目录,如果您打算将整个项目复制到部署到生产Web服务器,这是方便的。



为了使用 InheritanceManager ,模型需要稍微重构:



<$从django.db导入模型中的$ p code从django.contrib.auth.models导入
从datetime导入的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b get_upload_file_name ='images /'#我添加到调试模型

class BaseImage(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to = get_upload_file_name)
caption = models.CharField(max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

objects = InheritanceManager()

class BackgroundImage(BaseImage):
pass

class ProfilePicture(BaseImage):
pass

class Album(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length = 200)
pub_date = models.DateTimeField(default = datetime.now)

class Meta:
ordering = ['-pub_date']
verbose_name_plural =('Albums')

def __unicode __(self )
return self.name

class Photo(BaseImage):
album = models.ForeignKey(Album,default = 3)

所有的图像模型现在都从一个常见的超类继承,创建一个 InheritanceManager 。我也将所有重复的属性提升到超类,但这并不是绝对必要的,使用 InheritanceManager 表示<$ c $中不存在的任何属性c> BaseImage 仍然可以在模板中访问。



要检索由 -pubdate

  BaseImage.objects.select_subclasses()。order_by( -  pub_date)

要在视图中使用:

  def recentImages(request):
r = BaseImage.objects.select_subclasses()。order_by( - pub_date)[:20]
返回render_to_response(recentImages.html,{imageList :r})

要在模板中使用:

  {%for imageList%} 
< img src ={{photo.image.url}}/>
{%endfor%}

这是你想要的东西吗? p>

编辑



以下代码仍然可以正常工作,新型号: / p>

  class UserProfile(models.Model):
user = models.OneToOneField(User)
permanent_address = models .TextField()
temporary_address = models.TextField()
profile_pic = models.ForeignKey(ProfilePicture)
background_pic = models.ForeignKey(BackgroundImage)

只需确定 ForeignKey 关系中最后两个模型的名称正确! p>

Please have a look at my models.

class BackgroundImage(models.Model):
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to=get_upload_file_name)
    caption = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

class ProfilePicture(models.Model):
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to=get_upload_file_name)
    caption = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

class Album(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = ('Albums')

    def __unicode__(self):
        return self.name

class Photo(models.Model):
    user = models.ForeignKey(User)
    album = models.ForeignKey(Album, default=3)
    image = models.ImageField(upload_to=get_upload_file_name)
    caption = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

How do I get all the images of Photo, ProfilePicture and BackgroundImage from their image field in one set. And then filter them by -pub_date to display in the template? Please help me out. Will be much much appreciated! Thank you.

Edit

N.B: I need ProfilePicture and BackgroundImage to work with the UserProfile like this:

from django.db import models
from django.contrib.auth.models import User
from profile_picture.models import ProfilePicture
from background_image.models import BackgroundImage

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    permanent_address = models.TextField()
    temporary_address = models.TextField()
    profile_pic = models.ForeignKey(ProfilePicture)
    background_pic = models.ForeignKey(BackgroundImage)

    def __unicode__(self):
        return self.user.username

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

解决方案

There is an InheritanceManager provided as part of django-model-utils which allows you to do this, see docs.

To install in Linux / Mac:

sudo pip install django-model-utils

Annoyingly, installing using easy_install or pip on windows is not quite as straight forward, see: How do I install Python packages on Windows?. A quick and dirty method is to download the django-model-util/ directory from here into the top directory of your django project, this is handy if you intend to copy the entire project across for deployment to a production webserver.

In order to use the InheritanceManager, the models need to be refactored slightly:

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from model_utils.managers import InheritanceManager

get_upload_file_name = 'images/' # I added this to debug models

class BaseImage(models.Model):
    user = models.ForeignKey(User)
    image = models.ImageField(upload_to=get_upload_file_name)
    caption = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

    objects = InheritanceManager()

class BackgroundImage(BaseImage):
    pass

class ProfilePicture(BaseImage):
    pass

class Album(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=datetime.now)

    class Meta:
        ordering = ['-pub_date']
        verbose_name_plural = ('Albums')

    def __unicode__(self):
        return self.name

class Photo(BaseImage):
    album = models.ForeignKey(Album, default=3)

All the Image models now inherit from a common super class which creates an instance of the InheritanceManager. I've also moved up all the duplicated attributes into the superclass, but this isn't strictly necessary, using InheritanceManager means that any attributes which are not present in BaseImage can still be accessed in the template.

To retrieve a list ordered by -pubdate:

BaseImage.objects.select_subclasses().order_by("-pub_date")

To use in a view:

def recentImages(request):
    r = BaseImage.objects.select_subclasses().order_by("-pub_date")[:20]
    return  render_to_response("recentImages.html", { "imageList" : r })

To use in a template:

{% for photo in imageList %}
  <img src="{{ photo.image.url }}" />
{% endfor %}

Is this something like what you are looking for?

Edit

The following code will still work fine, with the new models:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    permanent_address = models.TextField()
    temporary_address = models.TextField()
    profile_pic = models.ForeignKey(ProfilePicture)
    background_pic = models.ForeignKey(BackgroundImage)

Just make sure the names of the last two models in the ForeignKey relationship are correct!

这篇关于django - 从不同的模型字段名获取一组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆