小编Pau*_*oon的帖子

如何使用 Django 查询集预取@property?

我想将模型属性预取到 Django 中的查询集。有没有办法做到这一点?

以下是三个模型:

class Place(models.Model):
    name = models.CharField(max_length=200, blank=True)
    @property
    def bestpicurl(self):
        try:
            return self.placebestpic.picture.file.url
        except:
            return None

class PlaceBestPic(models.Model):
    place = models.OneToOneField(Place)
    picture = models.ForeignKey(Picture, on_delete=models.CASCADE)

class Picture(models.Model):
    file = ImageField(max_length=500, upload_to="/images/")
Run Code Online (Sandbox Code Playgroud)

我需要类似的东西:

qs = Place.objects.all().select_related('bestpicurl')
Run Code Online (Sandbox Code Playgroud)

任何线索如何做到这一点?谢谢!

python django prefetch django-select-related

6
推荐指数
1
解决办法
3217
查看次数

Django 模型 OneToOneField:管理员中的“此字段是必需的”错误

当我在 Admin 中打开“Placating”条目,并在对任何字段进行更改后尝试保存它时,Django admin 在字段“Pic”上方显示“This field is required”。

class Placerating(models.Model):
    theplace = models.ForeignKey('ThePlace', on_delete=models.CASCADE, null=True, related_name='placeratings')
    pic = models.OneToOneField('fileupload.Picture', on_delete=models.SET_NULL, null=True)
    def __unicode__(self):
            return self.theplace.name

class Picture(models.Model):
    def set_upload_to_info(self, path, name):
        self.upload_to_info = (path, name)
    file = ImageField(max_length=500, upload_to=user_directory_path)
    def filename(self):
        return os.path.basename(self.file.name)
    theplace = models.ForeignKey(ThePlace, null=True, blank=True, related_name='pictures')
    def __unicode__(self):
        return str(self.id)
    def save(self, *args, **kwargs):
        super(Picture, self).save(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

我用表单创建了没有问题的条目,所以我不明白为什么管理员现在要求填写此字段。

python django model django-admin

5
推荐指数
1
解决办法
1820
查看次数

Pillow 返回错误:“IOError:图像文件被截断(6 个字节未处理)”

我使用 Pillow 4.1.1 和 Python 2.7/Django 1.9

我的网站上有成千上万张用户上传的图片,我使用枕头从模板生成缩略图。

例如:

{% thumbnail apicture.file "1200x350" crop="center" as im %}
    <img src="{{ im.url }}" width=100%>
{% endthumbnail %}
Run Code Online (Sandbox Code Playgroud)

直到本周,它都运行良好。Django 现在显示此错误:

IOError: image file is truncated (6 bytes not processed)
Run Code Online (Sandbox Code Playgroud)

在 stackoverflow 上找到的解决方案不起作用,因为它们都适用于视图而不是模板(例如 ImageFile.LOAD_TRUNCATED_IMAGES = True)。

有没有一种简单的方法可以识别哪些图片会产生此错误?如何解决这个错误?

这是完整的回溯:

Internal Server Error: /trip/province-dublin-2034
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)    
  File "C:\Terradiem\terradiem\trip\views.py", line 300, in trip …
Run Code Online (Sandbox Code Playgroud)

python django thumbnails python-imaging-library pillow

4
推荐指数
1
解决办法
3585
查看次数

Celery 击败进程在启动时分配大量内存

我在 Heroku 上运行 Django 1.9 网站,使用 Celery 3.1.23。RabbitMQ 用作代理。

重新启动beatworker后,内存使用量始终在497Mb左右。这会导致频繁出现错误 R14(超出内存配额),因为它很快就会达到 512Mb 限制。

如何分析启动时内存中的内容?即重新启动时如何获取内存中内容的详细信息?

以下是使用 Heroku log-runtime-metrics 测试版获得的内存消耗的详细信息:

heroku/beat.1:
source=beat.1 dyno=heroku.52346831.1ea92181-ab6d-461c-90fa-61fa8fef2c18
sample#memory_total=497.66MB
sample#memory_rss=443.91MB
sample#memory_cache=20.43MB
sample#memory_swap=33.33MB
sample#memory_pgpgin=282965pages
sample#memory_pgpgout=164606pages
sample#memory_quota=512.00MB 
Run Code Online (Sandbox Code Playgroud)

memory django heroku rabbitmq celery

3
推荐指数
1
解决办法
912
查看次数

用Django识别哪个多边形包含一个点?

我需要快速识别 Django 1.9 中一组点属于哪些多边形。

第一个选项是循环遍历所有多边形并检查它们包含哪些点:

for countrypolygon in countrypolygons:
    placesinthecountry = Place.objects.filter(lnglat__intersects=countrypolygon.geom)
Run Code Online (Sandbox Code Playgroud)

这需要很多时间,因为我需要循环遍历很多多边形。

是否可以做相反的事情,即循环遍历每个点并立即获取包含该点的多边形?

python django polygon geodjango intersect

3
推荐指数
1
解决办法
1753
查看次数

基于键过滤 Python 中的字典列表

我需要过滤字典列表以仅保留具有名为“子项”的键的字典。下面是一个列表示例:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}, {u'id': 5649}]
Run Code Online (Sandbox Code Playgroud)

这是我需要获得的:

[{u'id': 5650, u'children': [{u'id': 4635}]}, {u'id': 5648, u'children': [{u'id': 67}, {u'id': 77}]}]
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的:

dict((k, data[k]) for k in keys if k in data)
Run Code Online (Sandbox Code Playgroud)

而我得到的,这并不好:

[{u'children': [{u'id': 4635}]}, {u'children': [{u'id': 67}, {u'id': 77}]}, {}]
Run Code Online (Sandbox Code Playgroud)

有什么线索吗?提前致谢!

python dictionary list

2
推荐指数
1
解决办法
8058
查看次数