使用模型名称和外键模型之间的区别 [英] Difference between using name of model and model for ForeignKey

查看:46
本文介绍了使用模型名称和外键模型之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django文档项中,用于ForeignKey ,它说:

如果需要在尚未定义的模型上创建关系,则可以使用模型的名称,而不是模型对象本身:

例如名称

  class Car(models.Model):制造商=模型.ForeignKey('制造商') 

或对象

  class Car(models.Model):制造商=模型.ForeignKey(制造商) 

这两个变体之间有什么区别?

解决方案

您的第二个示例直接引用该类本身,并要求在使用该类之前定义或导入该类,而第一个示例将使用Django的模型加载框架.

通常,直接引用该类是可以的.在不太可取或不可能的情况下(例如,如果稍后在同一文件中定义制造商,或者如果导入类会导致循环导入产生问题),则字符串语法将使您可以合理地建立关系./p>

In the Django docs entry for ForeignKey, it says:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

e.g. name

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')

or object

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer)

What is the difference between these two variants?

解决方案

Your second example refers directly to the class itself, and requires that the class be defined or imported before you use it, while the first will use Django's model loading framework.

Usually, referring to the class directly is fine. In instances where it's not preferable or possible (if you are, for example, defining Manufacturer later in the same file, or if importing the class would cause issues with circular imports), the string syntax will let you set up the relationship sanely.

这篇关于使用模型名称和外键模型之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆