【问题标题】:Using id (Primary Key) of a Model as ForeignKey when creating new model instances in Django through shell通过 shell 在 Django 中创建新模型实例时使用模型的 id(主键)作为 ForeignKey
【发布时间】:2014-03-19 09:27:09
【问题描述】:

出于说明目的,仅提供两个普通模型:

class PrimaryModel(models.Model):
    foo = models.CharField(max_length=50, unique=True)

class SecondaryModel(models.Model):
    bar = models.ForeignKey(PrimaryModel)

现在尝试在 shell 中创建实例:

>>> import testapp.models
>>> a=testapp.models.PrimaryModel(foo="Test1")
>>> a.save()
>>> b=testapp.models.SecondaryModel(bar=1)

...当然还有错误:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/base.py", line 405, in __init__
    setattr(self, field.name, rel_obj)
  File "/home/pkaramol/Workspace/django-env/lib/python3.3/site-packages/django/db/models/fields/related.py", line 337, in __set__
    self.field.name, self.field.rel.to._meta.object_name))
ValueError: Cannot assign "1": "SecondaryModel.bar" must be a "PrimaryModel" instance.

问题是为什么我们不能使用 PrimaryModel 的 id(如上面的错误示例)而必须使用实例? 还尝试使用to_field 字段,如

class SecondaryModel(models.Model):
    bar = models.ForeignKey(PrimaryModel, to_field='foo')

但这并没有改变情况。

【问题讨论】:

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


【解决方案1】:

如果你想使用 PrimaryModel 的 id,你应该这样做:

b=testapp.models.SecondaryModel(bar_id=1)

【讨论】:

    【解决方案2】:

    这个怎么样。

    >>> import testapp.models
    >>> a=testapp.models.PrimaryModel(foo="Test1")
    >>> a.save()
    >>> b=testapp.models.SecondaryModel()
    >>> b.bar_id = 1
    >>> b.save()
    

    实际上,您只需在外键名称中添加 _id 即可访问 fk id。只需创建模型,然后手动设置 fk_id 然后保存

    【讨论】:

      猜你喜欢
      • 2013-02-11
      • 1970-01-01
      • 2017-03-04
      • 2014-07-23
      • 1970-01-01
      • 2021-03-09
      • 2021-06-19
      • 2013-03-25
      • 2020-09-13
      相关资源
      最近更新 更多