django模型id何时生成?

时间:2016-05-13 02:15:17

标签: django django-models slug

我正在创建一个应用程序,我希望通过哈希字符串访问图片(以防止人们猜测/访问其他照片)。为此,我使用以下方法:

class PhotoModel(models.Model):
    name = models.CharField(max_length=256)
    slg = models.SlugField()

    def save(self, *args, **kwargs):
        if not self.slg:
            self.slg = slugify(my_own_hash_function(str(self.id)))
        super(PhotoModel, self).save(*args, **kwargs)

这种方法有效,但我无法弄清楚原因。在django模型中'id'生成?这是为对象创建不可思议的URL的正确方法吗? (我将在散列函数中添加一个salt以便以后增加安全性)

1 个答案:

答案 0 :(得分:0)

如果id字段是自动增量字段,则ID实际上由数据库生成。它通过数据库中可用的机制返回到django,例如在mysql中这可能是LAST_INSERT_ID()

如果你像你一样覆盖模型中的save方法,那么在你执行#@author: Long Duong #Using this : http://cvxopt.org/userguide/coneprog.html#quadratic-programming #Need to install cvxopt using (pip install cvxopt --user) from cvxopt import matrix, solvers # Need to MODIFY the value here # Hold the value of x1,x2,x3,x4,x5 xi = matrix([0.5,0.6,0.7,0.8,0.9]) # Hold the value for a,b,c,d,e cons = matrix([0.2,0.2,0.2,0.2,0.2]) ### Main part #### # Ensure the contrain: x1' + x2' + x3' + x4' + x5' = 1 A = matrix([1.0,1.0,1.0,1.0,1.0], (1,5)) b = matrix(1.0) # Ensure the contrain: cons[i] -0.1 < x'[i] < cons[i] + 0.1 G = matrix([[1.0,0.0,0.0,0.0,0.0], [-1.0,0.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0,0.0], [0.0,-1.0,0.0,0.0,0.0], [0.0,0.0,1.0,0.0,0.0], [0.0,0.0,-1.0,0.0,0.0], [0.0,0.0,0.0,1.0,0.0], [0.0,0.0,0.0,-1.0,0.0], [0.0,0.0,0.0,0.0,1.0], [0.0,0.0,0.0,0.0,-1.0]]).T temp = [] for i in range(5): temp.append(cons[i] + 0.1) temp.append(-1 * (cons[i] - 0.1)) h = matrix(temp) # Now need to solve the main function to minimize sum((x'[i]-xi[i])^2) # P is kind of identity matrix since (x-a)^2 = x^2 - 2ax + a^2 P = 2 * matrix([[1.0,0.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0,0.0], [0.0,0.0,1.0,0.0,0.0], [0.0,0.0,0.0,1.0,0.0], [0.0,0.0,0.0,0.0,1.0]]) q = -2 * xi # # All done sol=solvers.qp(P, q, G, h, A, b) print "[RESULT] :" print sol['x'] 之前,id将是未定义的,但它将在之后定义。

生成ID的另一种方法是使用UUID字段。在这种情况下,django通过调用super(PhotoModel, self).save(*args, **kwargs)

生成id

UUID字段是不可取的,如果您将uuid字段作为主键,则不需要使用slug字段,但使用UUID还有其他缺点。 UUID的优点和缺点在stackoverflow的其他地方被广泛讨论,我认为我不需要进一步讨论。

至于问题“这是为对象创建不可饶恕的URL的正确方法吗?”如果不查看哈希函数,这个问题就无法正确回答。无论如何,这应该在一个单独的问题上发布。