简体   繁体   English

Django模型中的外键和主键关系

[英]foreign key and primary key relation in models in django

These models are in two different applications in django. 这些模型在django中有两个不同的应用程序。 I had created the primary key and foreign key relation between the two tables, but the output is not desired output. 我已经在两个表之间创建了主键和外键关系,但是输出不是理想的输出。

class User(models.Model):
    user_name = models.CharField( max_length=255, default=None)
    email = models.CharField( max_length=255, default=None)
    mobile_number = models.IntegerField( default=0)
    created_on = models.DateTimeField( auto_now=True)

class Todo(models.Model):
    title = models.CharField( max_length=255, default=None)
    description = models.CharField( max_length=255, default=None)
    created_on = models.DateTimeField(auto_now=True)
    user = models.ForeignKey('Account.User',on_delete=models.CASCADE)

Suppose I created a entry in the User table and the id assigned is 1 , but I can also create a entry in the Todo table with user_id = 2 (which is not a valid value according to the rule ), and the entry is created. 假设我在User表中创建了一个条目,并且分配的id为1 ,但是我也可以在Todo表中创建一个user_id = 2的条目(根据规则,这不是有效值),并且创建了该条目。 Can any one suggest why? 有人可以建议原因吗?

In Python shell: 在Python Shell中:

from Account.models import User
my_user = ( user_name = "Abhis", email = "aa@aa.com", mobile_number = "9999999999", created_on = datetime.datetime.today())
my_user.save()    

# it will create a row with id 1.
from ToDo.models import Todo
my_todo = ( title = "title", description = "description", created_on = datetime.datetime.today(), user_id = 4)
my_todo.save()
# the row with this user_id = 4 is created, which must be illegal 

The django documentation states that this will not happen and it will throw DoesNotExist exception. django文档指出不会发生这种情况,并且会引发DidsNotExist异常。 Kindly check the link below 请检查下面的链接

Django raises DoesNotExist when consulting an empty ForeignKey field or key that does not exist 当查询空的外键字段或不存在的键时,Django引发DoesNotExist

But if you are connecting to a database that exists, and it has values which are not proper foreign keys that is also mentioned in the below link. 但是,如果要连接到存在的数据库,并且该数据库的值不是正确的外键,则在下面的链接中也提到了该值。 It clearly states that the model is wrong and should be changed in such a scenario.Link below 它明确指出该模型是错误的,在这种情况下应进行更改。

documentation: invalid foreign key and select_related 文档:无效的外键和select_related

When i tried to assign a random value to a foreign key it threw ValueError. 当我尝试为外键分配随机值时,它抛出了ValueError。 Can you check if your DB does not have an entry with user_id=4 . 您能否检查您的数据库是否没有user_id=4的条目。

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

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