简体   繁体   English

Django 模型将外键设置为另一个模型的字段

[英]Django Model set foreign key to a field of another Model

Is there any way to set a foreign key in django to a field of another model?有没有办法在 django 中将外键设置为另一个模型的字段

For example, imagine I have a ValidationRule object.例如,假设我有一个 ValidationRule 对象。 And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)而且我希望规则定义要验证另一个模型中的哪些字段(以及其他一些信息,例如它是否可以为空、数据类型、范围等)

Is there a way to store this field-level mapping in django?有没有办法在 django 中存储这个字段级映射?

I haven't tried this, but it seems that since Django 1.0 you can do something like:我还没有尝试过,但似乎从 Django 1.0 开始,您可以执行以下操作:

class Foo(models.Model):
    foo = models.ForeignKey(Bar, to_field='bar')

Documentation for this is here .这方面的文档在这里

Yes and no.是和不是。 The FK relationship is described at the class level, and mirrors the FK association in the database, so you can't add extra information directly in the FK parameter. FK关系是在类级别描述的,镜像数据库中的FK关联,所以不能直接在FK参数中添加额外的信息。

Instead, I'd recommend having a string that holds the field name on the other table:相反,我建议使用一个字符串来保存另一个表上的字段名称:

class ValidationRule(models.Model):
    other = models.ForeignKey(OtherModel)
    other_field = models.CharField(max_length=256)

This way, you can obtain the field with:这样,您可以通过以下方式获取该字段:

v = ValidationRule.objects.get(id=1)
field = getattr(v, v.other_field)

Note that if you're using Many-to-Many fields (rather than a One-to-Many), there's built-in support for creating custom intermediary tables to hold meta data with the through option.请注意,如果您使用多对多字段(而不是一对多),则内置支持创建自定义中间表以使用through选项保存元数据。

You need to use "to_field" in "models.ForeignKey()" to set other field in other model:您需要在“models.ForeignKey()”中使用“to_field”来设置其他模型中的其他字段:

ForeignKey.to_field ForeignKey.to_field

The field on the related object that the relation is to.关系所针对的相关对象上的字段。 By default, Django uses the primary key of the related object.默认情况下,Django 使用相关对象的主键。 If you reference a different field, that field must have unique=True.如果您引用不同的字段,则该字段必须具有 unique=True。

For example, as a foreign key, "categories" field in "Product" model references "name" field in "Category" model as shown below.例如, “Product”模型中的“categories”字段作为外键引用“Category”模型中的“name”字段,如下所示。 *Be careful, the referenced field "name" in "Category" model needs "unique=True" or "primary_key=True" otherwise there is an error: *注意, “Category”模型引用的字段“name”需要“unique=True”“primary_key=True”否则会报错:

# "models.py"

from django.db import models
                                            # "unique=True" or
class Category(models.Model):               # "primary_key=True" are needed 
    name = models.CharField(max_length=100, unique=True)
    
class Product(models.Model):
    name = models.CharField(max_length=100)                
    categories = models.ForeignKey(
        Category, 
        to_field='name', # ← Here
        on_delete=models.PROTECT
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM