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")
我正在尝试使用以下方法测试方法:
def test_get_subsribers(self):
user1= User.objects.create_user('Maria','j@j.com','j1')
user4= User.objects.create_user('Giannis','m@m.com','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的新手,我不知道如何解决这个问题。
答案 0 :(得分:1)
您尝试将未保存的订阅者添加到巡视中。
您需要在sub.save()
tour.subscribers.add(sub)
在添加tour
之前,还必须保存sub
。
这样做的原因是处理多对多关系(see docs)的附加表。此表存储两个外键 - 一个用于Tour
,另一个用于Subscribers
。要将行保存到此表中,Tour和Subscriber应存在于数据库