相关疑难解决方法(0)

Django:保存时,如何检查字段是否已更改?

在我的模型中,我有:

class Alias(MyBaseModel):
    remote_image = models.URLField(max_length=500, null=True, help_text="A URL that is downloaded and cached for the image. Only
 used when the alias is made")
    image = models.ImageField(upload_to='alias', default='alias-default.png', help_text="An image representing the alias")


    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue()))
            except IOError :
                pass
Run Code Online (Sandbox Code Playgroud)

这首次remote_image变化很有效.

当有人修改remote_image了别名时,如何获取新图像?其次,是否有更好的方法来缓存远程图像?

django caching image django-models

273
推荐指数
13
解决办法
14万
查看次数

Django一旦被访问就会缓存相关的ForeignKey和ManyToManyField字段吗?

鉴于以下模型,Django是否在第一次访问后缓存相关对象?

class Post(models.Model):
    authors = models.ManyToManyField(User)
    category = models.ForeignKey(Category)
Run Code Online (Sandbox Code Playgroud)

例如:

post = Post.objects.get(id=1)

# as i understand this hits the database
authors1 = post.authors.all()
# does this his the database again?
authors2 = post.authors.all()

# as i understand this hits the database
category1 = post.category
# does this hit the database again?
category2 = post.category
Run Code Online (Sandbox Code Playgroud)

注意:目前正在使用Django 1.3,但很高兴知道其他版本中可用的内容.

python django django-models

10
推荐指数
1
解决办法
3854
查看次数

有没有办法检查相关对象是否已经被获取?

我希望能够使用select_related或检查是否已获取相关对象prefetch_related,以便可以相应地序列化数据。这是一个例子:

class Address(models.Model):
    street = models.CharField(max_length=100)
    zip = models.CharField(max_length=10)

class Person(models.Model):
    name = models.CharField(max_length=20)
    address = models.ForeignKey(Address)

def serialize_address(address):
    return {
        "id": address.id,
        "street": address.street,
        "zip": address.zip
    }

def serialize_person(person):
    result = {
        "id": person.id,
        "name": person.name
    }
    if is_fetched(person.address):
        result["address"] = serialize_address(person.address)
    else:
        result["address"] = None

######

person_a = Person.objects.select_related("address").get(id=1)
person_b = Person.objects.get(id=2)

serialize_person(person_a) #should be object with id, name and address
serialize_person(person_b) #should be object with only id and name
Run Code Online (Sandbox Code Playgroud)

在此示例中,该功能is_fetched正是我要寻找的。我想确定person对象是否已经具有解析地址,并且只有在具有解析地址的情况下,也应该对其进行序列化。但是,如果没有,则不应再执行任何数据库查询。

那么有没有办法在Django中实现呢?

python django django-queryset django-select-related

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