如何在模型中构建字段值,该模型源自另一个模型中的值

时间:2015-12-23 09:24:00

标签: python django django-models exists distinct-values

系统模型有派对模型

class Party(models.Model):
    name = models.CharField(max_length=128)
    our_reference = models.CharField(max_length=128)

彼得是一个派对,另一个同名的人也被称为彼得。字段“our_reference”应使用前三个字符,后跟一个int,如PET1。第二个彼得将是PET2。增加了第三人称为Petras。他将成为PET3。

使用Levenshtein模块(https://rawgit.com/ztane/python-Levenshtein/master/docs/Levenshtein.html)我们需要在插入一方时测试该方是否已经存在,例如 -

def get_similar_items(mod, field, string, similarity_ratio=0.6, limit=None): """ Get similar items for a specific model Example usage: similar = get_similar_items(Entry, 'title', 'Espresso is good for you', 0.5, 10) var = Entry.objects.filter(id__in=similar) """ similar_list_id = [] v = ContentType.objects.get_for_model(mod) c = v.model_class() for i in c.objects.all(): if ratio(string, getattr(i,field)) > similarity_ratio: similar_list_id.append(i.id) return similar_list_id[:limit] https://djangosnippets.org/snippets/288/

如果该方存在,请不要使用新的int号,而是使用旧的,即PET1作为参考。如果该方不存在,请制作新的参考资料PET4。

编辑问题以使用例更清晰。如何实施?

1 个答案:

答案 0 :(得分:0)

听起来不是在一个名为our_reference的字段中将派对的首字母和指令号一起添加,最好只保存参考号,因为你可以从fk参加聚会。

这样可以更容易地增加指令编号。

所以将our_reference更改为int字段。

每当您想要添加新案例时,请检查该方是否已存在。您可能希望拥有除名称之外的标识符,因为两个人可以具有相同的名称。

如果该方不存在,请创建一个并抓取名称str(party.name[3:]).upper()的前三个字符。

要获取新的指令编号,您可以找到该方已经使用related_names的所有指令。

写下以下内容:

  

new_instruction_number_for_party = max(party.instructions.all()。values_list(' our_reference'))+ 1

最后,在模板中显示总文件引用时,将our_reference和前三个字母添加到上下文中,并在模板中添加{{ party_initials }}{{ num_of_initial }}/{{ our_reference }}