如何在Django模型中轻松创建计算字段?

时间:2016-03-13 23:11:23

标签: python django django-models

No, I don't want a propertyI really don't。我想要的就是我的要求。

由于子类化要求,我正在寻找一种方法从一组另外两个中生成一个字段并将此计算存储在数据库中。不是Python中的属性,不是SQL计算,是在数据库中保存和存储时更新的预先计算的字段。

例如:

class Help(models.Model):
    title = models.TextField()
    body = models.TextField()

class SoftwareHelp(Help):
    about_software = models.ForeignKey('Software')

无论用户在title字段中输入什么内容,我都希望在点击保存后说出“帮助”。实际上,代码有更多的字段,但这解释了原则。

我知道可以通过覆盖save()方法来做到这一点,但是想确保我没有保存到数据库两次,并想知道是否还有其他更好的方法。

1 个答案:

答案 0 :(得分:2)

我认为最简单的方法是覆盖void loader(char *word, char *translation) { struct node *tempNode = (struct node*)malloc(sizeof(struct node)); struct node *current; struct node *father; tempNode->word = word; tempNode->translation = translation; tempNode->leftChild = NULL; tempNode->rightChild = NULL; /* If tree is empty */ if(root == NULL) { root = tempNode; } else { current = root; father = NULL; } while(1) { father = current; /* Goes to the left side of the tree */ if(strcmp(word,father->word) < 0) { current = current->leftChild; /* Insert to the left */ if(current == NULL) { father->leftChild = tempNode; return; } } else { current = current->rightChild; if(current == NULL) { father->rightChild = tempNode; return; } } } } void add(char *word, char *translation) { struct node *tempNode = (struct node*)malloc(sizeof(struct node)); struct node *current; struct node *father; tempNode->word = word; tempNode->translation = translation; tempNode->leftChild = NULL; tempNode->rightChild = NULL; /* If tree is empty */ if(root == NULL) { root = tempNode; } else { current = root; father = NULL; } while(1) { father = current; /* Goes to the left side of the three */ if(strcmp(word,father->word) < 0) { current = current->leftChild; /* Insert to the left */ if(current == NULL) { father->leftChild = tempNode; printf("WORD ADDED\n"); return; } else { printf("WORD ALREADY EXISTS\n"); } } else { current = current->rightChild; if(current == NULL) { father->rightChild = tempNode; printf("WORD ADDED\n"); return; } else { printf("WORD ALREADY EXISTS\n"); } } } } void mark(char *word) { struct node *tempWord = search(word); if(tempWord != NULL) { tempWord->marker = true; printf("%s MARKED\n", tempWord->word); } else { printf("WORD NOT FOUND\n"); } } void alphanum_list() { struct node *tempNode = root; if(tempNode != NULL) { alphanum_list(tempNode->leftChild); printf("%s\n", tempNode->word); alphanum_list(tempNode->rightChild); } printf("END OF LIST\n"); } void mark_list() { struct node *tempNode = root; if(tempNode != NULL) { mark_list(tempNode->leftChild); if(tempNode->marker == true) { printf("%s\n", tempNode->word); } mark_list(tempNode->rightChild); } printf("END OF MARKED ENTRIES\n"); } 方法。我没有看到为什么它应该保存到数据库两次的原因。

save