简体   繁体   English

将 foreignKey id 更改为另一个 Field

[英]Change the foreignKey id to another Field

I don't know if there is a logic for this, because i seen it before when I programed with C# and VB, but in Django, it's seems hard to get it.不知道有没有这样的逻辑,因为之前用C#和VB编程的时候看到过,但是在Django,好像很难搞定。

So what I want to?那我想要什么? I want the table in database save the name and not the id of the foreignKey.我希望数据库中的表保存名称而不是外键的 ID。 And this is the model.py这是 model.py

from pyexpat import model
from statistics import mode
from venv import create
from django.db import models
from django.contrib.auth.models import User
from django.db.models.base import Model
from django.forms import IntegerField



class Post(models.Model):
    name = models.CharField(max_length=150)

    def __str__(self):
        return str(self.name)


class Person(models.Model):
    post = models.ForeignKey(Post , on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return f"({self.name} is {self.post})"



class Room(models.Model):
    name = models.CharField(max_length= 150, unique = True)

    def __str__(self):
        return str(self.name)


class Classification(models.Model):
    name = models.ForeignKey(Person, on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    date = models.DateField(auto_created=False)
    create_date = models.DateTimeField(auto_created=True)

    def __str__(self):
       return f"({self.name} Take {self.room}  at {self.date})"

The result in Database table:数据库表中的结果:

enter image description here在此处输入图像描述

What I want to see in the database table, is that Django replace the id's in name_id column with names, and room_id with room names我想在数据库表中看到的是 Django 用名称替换 name_id 列中的 id,用房间名称替换 room_id

Is that possible?那可能吗?

You can use the to_field=… parameter [Django-doc] to specify to what the ForeignKey should point.您可以使用to_field=…参数[Django-doc]来指定ForeignKey应该指向的内容。 This should always be a unique field in the targetting model. So you can use:这应该始终是目标 model 中的唯一字段。因此您可以使用:

class Classification(models.Model):
    person = models.ForeignKey(Person, to_field='name', on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    date = models.DateField()
    create_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
       return f'({self.person_id} Take {self.room}  at {self.date})'

You should likely however recreate the migrations for the Classification model, and thus let this create a ForeignKey that references the name of the Person model.但是,您可能应该为Classification model 重新创建迁移,从而创建一个引用Person name ForeignKey的外键。

You can here use self.person_id to avoid making an extra query to load the Person object. This will thus improve the efficiency when calling the __str__ method of a Classification object.这里可以使用self.person_id来避免额外查询加载Person object,从而提高调用Classification object的__str__方法时的效率。

First you need to make the name a Pk in the Model primary_key=True then in the ForeignKey set the to_field='name'首先,您需要在 Model primary_key=True中将名称设为 Pk,然后在 ForeignKey 中设置to_field='name'

very easy...很简单...

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

相关问题 django change外键字段 - django change foreignkey Field FormWizard中具有MultiValueField的ForeignKey字段与另一个ForeignKey - ForeignKey field with another ForeignKey in FormWizard with MultiValueField 如何通过Django中的另一个ForeignKey使用ForeignKey字段获取对象? - How to get objects using a ForeignKey field through another ForeignKey in Django? 为什么Django在ForeignKey字段名称中要求“ _id”? - Why Django requires “_id” in the name of ForeignKey field? Django:For ForeignKey id 字段的完整性错误不是 null - Django: Integrity error not null for ForeignKey id field 序列化程序使用外键显示 id 而不是字段名称 - Serializer is displaying id instead of field names with Foreignkey Peewee:使用其他名称更改“ Id”字段 - Peewee: change “Id” field with another name Django更新queryset以更改ForeignKey的ID - Django update on queryset to change ID of ForeignKey Django,管理面板,一个可用于选择的 ForeignKey 字段的值依赖于在另一个 ForeignKey 字段中选择的值 - Django, admin panel, dependence of the values of one ForeignKey field available for selection on the value selected in another ForeignKey field 如何限制 Django raw_id_field 的外键选择 - How to limit choices of ForeignKey choices for Django raw_id_field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM