Django的。选择特定字段-一对多关系

时间:2018-07-27 13:12:34

标签: python django python-3.x django-models

我有两个表,并且想要一对多地释放它们。 一合一-许多统计。

我尝试选择字段,但是它不起作用。

我的外键始终是 Unit.name 。 我想将 Unit.id 用作 ForeignKey !!

我认为 Unit.id 不可能如此,对于我尝试了另一个字段 Unit.name2 的测试,它也不起作用。 https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.to_field

class Unit(models.Model) :

    id = models.AutoField(primary_key=True)
    name = models.CharField( max_length=20, unique=True)
    name2 = models.CharField( max_length=20, unique=True)
    rase = models.CharField( max_length=10 )

class Stat(models.Model) :

    id = models.AutoField(primary_key=True)
    unit_id = models.ForeignKey( Unit, to_field='name2', on_delete=models.CASCADE, verbose_name='unit_id',)
    attack_type = models.CharField( 'attack_type', max_length=10 )
    attack_speed = models.DecimalField( 'attack_speed', max_digits=5, decimal_places=4 )
    attack_number = models.IntegerField( 'attack_number' )

其他问题。 如果我将 Unit.name 保留为ForeignKey,将来我更改 Unit.name 时会发生什么?名称值是否将在所有相关表中更改?

这就是为什么我要使用 Unit.id 作为外键的原因,因为 Unit.id 不会更改,而 Unit.name 可以更改。

1 个答案:

答案 0 :(得分:0)

我还在单元模型的AutoField中添加了 unique = True

我也将 Unit.id 更改为 Unit.unit_id

似乎有效。

class Unit(models.Model) :

    unit_id = models.AutoField(primary_key=True, unique=True, verbose_name='unit_id', )
    name = models.CharField( max_length=20, unique=True)
    name2 = models.CharField( max_length=20, unique=True)
    rase = models.CharField( max_length=10 )

    def __str__( self ) :
        string = 'unit_id: {} - {}'.format(self.unit_id, self.name)
        return string

class Stat(models.Model) :
    stat_id = models.AutoField(primary_key=True)
    unit_id = models.ForeignKey( Unit, to_field='unit_id', on_delete=models.CASCADE, verbose_name='unit_id', )
    attack_type = models.CharField( 'attack_type', max_length=10 )
    attack_speed = models.DecimalField( 'attack_speed', max_digits=5, decimal_places=4 )
    attack_number = models.IntegerField( 'attack_number' )

    def __str__( self ) :
        string = '{0} {1} stat'.format(self.unit_id, self.attack_type)
        return string