Django - 创建自定义ID

时间:2017-08-20 17:30:30

标签: python django primary-key

我知道Django auto会为我的模型生成一个带有primary_key

的ID

而且我也知道,如果我想生成自定义ID,我应该这样做:

plotly_map <- ggplotly(q)
plotly_map$x$data[[2]]$text <- paste(Countryprofile$Countries,
                                     Countryprofile$count, 
                                     sep='<br />')
plotly_map

但是我如何更改此ID以使其看起来像library(plotly) library(ggmap) Countryprofile <- structure(list(Countries = c("USA", "India", "Europe", "LATAM", "Singapore", "Phillipines", "Australia", "EMEA", "Malaysia", "Hongkong", "Philippines", "Thailand", "New Zealand" ), count = c(143002, 80316, 33513, 3736, 2180, 1905, 1816, 921, 707, 631, 207, 72, 49)), .Names = c("Countries", "count"), row.names = c(NA, 13L), class = "data.frame") countries = geocode(Countryprofile$Countries) Countryprofile = cbind(Countryprofile,countries) mapWorld <- borders("world", colour="grey", fill="lightblue") q<-ggplot(data = Countryprofile) + mapWorld + geom_point(aes(x=lon, y=lat) ,color="red", size=3)+ geom_text(data = Countryprofile,aes(x=lon,y=lat,label=Countries)) plotly_map <- ggplotly(q) plotly_map$x$data[[2]]$text <- paste(Countryprofile$Countries, Countryprofile$count, sep='<br />') plotly_map

其中:

id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

1 个答案:

答案 0 :(得分:1)

我没有看到你为什么要这样做的原因,但是你可以做到。只需创建一个小函数来生成id并将其传递给您的字段。

import datetime
from uuid import uuid4
def create_id():
    now = datetime.datetime.now()
    return str(now.year)+str(now.month)+str(now.day)+str(uuid4())[:7]

然后在模型领域

id = models.CharField(primary_key=True, default=create_id, editable=False)

请记住将函数对象作为参数传递而不是可调用。