Django尝试在主键OneToOne列中添加“ _id”

时间:2019-05-03 10:06:15

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

刚刚启动Django。 我有2个模型。 Radusergroup和到期时间。用户名是Radusergroup上的主键,并且是一个onetoOne字段,到期时间为primary_key = True。 Django尝试在到期模型中查询username_id,尽管字段本身仅是username。

当我没有明确定义Managed = False时,它也会尝试将过期表中的用户名字段也从数据库更改为username_id。 我在这里做什么错了?

class Radusergroup(models.Model):
    username = models.CharField(max_length=64,primary_key=True)
    groupname = models.CharField(max_length=64)
    priority = models.IntegerField()
    class Meta:
        managed = False


class expiration(models.Model):
    username = models.OneToOneField(Radusergroup,on_delete=models.CASCADE, to_field='username', primary_key=True)
    expiration = models.DateTimeField()
    class Meta:
        managed = False
python .\manage.py shell
>>> help(expiration())
Help on expiration in module panel_app.models object:

class expiration(django.db.models.base.Model)
 |  expiration(*args, **kwargs)
 |
 |  expiration(username, expiration)
 |
 |  Method resolution order:
 |      expiration
 |      django.db.models.base.Model

 |      builtins.object
 |
 |  Methods defined here:
 |
 |  expiration = <django.db.models.query_utils.DeferredAttribute object>
 |  get_next_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=True, **
kwargs)
 |
 |  get_previous_by_expiration = _method(self, *, field=<django.db.models.fields.DateTimeField: expiration>, is_next=Fals
e, **kwargs)
 |
 |  username_id = <django.db.models.query_utils.DeferredAttribute object>
 |  ----------------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

感谢dirkgroten向我指出正确的方向。 添加db_column解决了我的问题

class expiration(models.Model):
    username = models.OneToOneField(Radusergroup,on_delete=models.PROTECT, to_field='username',db_column="username" , primary_key=True)