[英]Django - Primary Key field related to foreign key
我希望共享外鍵的Feature模型實例具有ID。 創建新功能時,我想自動增加該ID。
如果您從數據庫的功能表中查看此打印,則每個功能都有一個外鍵(shapefile_id),而那些共享相同shapefile_id的功能則具有唯一的ID(id_relat)
我想知道是否有比目前為止發現的更好的方法來處理此問題:
class Shapefile(models.Model):
filename = models.CharField(max_length=255)
class Feature(models.Model):
shapefile = models.ForeignKey(Shapefile)
id_relat = models.PositiveIntegerField(db_index=True)
def Meta(self):
unique_together = (("shapefile", "id_relat"),)
def save(self, *args, **kwargs):
if not self.id_relat: #assign incremented id only to new feature
self.id_relat = cal_id_relat(self.shapefile)
super(Feature, self).save(*args, **kwargs)
def cal_id_relat(shapefile):
ids_relat = Feature.objects.filter(shapefile=shapefile).order_by('-id_relat').values_list('id_relat',flat=True)
if ids_relat:
return ids_relat[0]+1
else:
return 0
我在此不喜歡的是,必須查詢所有功能以在cal_id_relat方法中獲得最高的id_relat。
您的Django應用程序可以在1個以上的線程中執行,因此您的方法具有潛在的危險。 可以同時調用cal_id_relat,並將為所有調用返回相同的ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.