2
這些模型在django中有兩個不同的應用程序。我創建了兩個表之間的主鍵和外鍵關係,但輸出不是所需的輸出。django模型中的外鍵和主鍵關係
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)
假設我創造了User
表中的條目,並分配id爲1
,但我也可以建立在Todo
表user_id = 2
一個條目(這是不按規則的有效值),和該條目已創建。任何人都可以建議爲什麼?
在Python外殼:
from Account.models import User
my_user = (user_name = "Abhis", email = "[email protected]", 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
分享您編寫的用於創建對象的代碼。 – badiya
其實這個字段是'user'而不是'user_id'。也請粘貼沒有任何語法錯誤的代碼.. –
user_id列是在數據庫本身中創建的,這就是爲什麼我使用它 –