无法分配“ 40”:“ Group.groupParent_id”必须是“ Group”实例

时间:2019-06-24 17:36:30

标签: python django

我想从我的组模型中添加组。这是关于父子关系的递归。

但是当我想创建一个有孩子的小组时。我有错误

我的模特:

class Group(models.Model):
    group_id = models.AutoField(primary_key=True)
    groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE)
    group_name = models.CharField(max_length=100, null=False, blank=False, unique=True)

views.py: 我的函数在第18行GroupParent_id上引发错误:

def add_group_fromcoa(request):  # add type and subtype of chart of account as first serie of group and subgroup

    # ------ Type adding -----
    types = ChartOfAccount.objects.order_by().values_list("field_type", flat=True).distinct()

    for type_types in types:

        upload_data = Group.objects.get_or_create(group_name=type_types,)

    types = ChartOfAccount.objects.order_by().values_list('field_subtype', flat=True).distinct()

    for type_types in types:
        looktype = ChartOfAccount.objects.filter(field_subtype=type_types).values('field_type').first()
        print("retour Groupe: {}".format(looktype['field_type']))
        looktyp= Group.objects.filter(group_name=looktype['field_type']).values('group_id').first()
        print("IDGroup: {}".format(int(looktyp['group_id'])))
        upload_data = Group.objects.get_or_create(
          group_name=type_types,
          groupParent_id=int(looktyp['group_id']))

    return redirect(home)

1 个答案:

答案 0 :(得分:1)

在Django中创建外键关系时,Djano的默认行为是将列名命名为<object_column_name>_id。因此,当您添加字段groupParent_id时,Django将数据库字段命名为groupParent_id_id。现在,当您在Django模型上具有外键时,您可以通过两种方式来引用该关系:可以使用对象,也可以使用数据库主键。如果使用模型中字段的名称,则引用必须是一个对象。但是,如果在末尾添加_id,则可以在尝试使用主键时使用它。如果将groupParent_id=int(looktyp['group_id'])更改为groupParent_id_id=int(looktyp['group_id']),则应该可以。