2012-11-27 125 views
0
class Subscribers(User): 
    date = models.DateField() 
    user = models.OneToOneField(User) 

class Tour(models.Model): 
    """ This is not the id is a User object 
    """ 
    owner_id = models.ForeignKey(User) 
    name = models.CharField(max_length=50, primary_key=True) 
    location = models.ManyToManyField(Location) 
    subscribers = models.ManyToManyField(Subscribers, related_name="sub") 

我試圖用測試方法:Django模型完整性錯誤

def test_get_subsribers(self): 
    user1= User.objects.create_user('Maria','[email protected]','j1') 
    user4= User.objects.create_user('Giannis','[email protected]','m1') 
    sub= Subscribers() 
    sub.user = user4 
    tour = Tour() 
    tour.owner_id = user1 
    tour.name = "Open Day" 
    tour.subscribers.add(sub) 
    self.assertEqual(get_subscribers("Open Day").count(),0) 

但我得到的是一個錯誤:

IntegrityError: insert or update on table "tour_tour_subscribers" violates foreign key constraint "tour_tour_subscribers_subscribers_id_fkey" 
DETAIL: Key (subscribers_id)=(10) is not present in table "tour_subscribers". 

我在Django新的和我不不知道如何解決這個問題。

回答

1

您嘗試將未保存的Subscriber添加到巡視中。

您需要tour.subscribers.add(sub)

tour調用sub.save()也必須加入sub之前保存。

原因是處理多對多關係的附加表格(see docs)。該表存儲兩個外鍵 - 一個用於Tour,另一個用於Subscribers。要將一行保存到此表中,遊覽和訂閱者都應該存在於數據庫中

+0

如果我想將其他訂閱者添加到遊覽中,該怎麼辦? – user1855165