django – TypeError:*之后的add()参数必须是序列,而不是订阅者
发布时间:2020-12-20 13:31:41 所属栏目:Python 来源:网络整理
导读:class Subscribers(User): date = models.DateField() user = models.OneToOneField(User)class Tour(models.Model): owner_id = models.ForeignKey(User) name = models.CharField(max_length=50) location = models.ManyToManyField(Location) subscribers
class Subscribers(User): date = models.DateField() user = models.OneToOneField(User) class Tour(models.Model): owner_id = models.ForeignKey(User) name = models.CharField(max_length=50) location = models.ManyToManyField(Location) subscribers = models.ManyToManyField(Subscribers,related_name="sub") 我试图在另一个文件中执行此操作: user1 = User.objects.create_user('John','j@j.com','j1') user2= User.objects.create_user('Mike','m@m.com','m1') user3= User.objects.create_user('kokoko','m1') user4= User.objects.create_user('lalal','m1') sub = Subscribers() tour = Tour() tour.id = "1" tour.name = "hello" tour.owner_id = user1 tour.subscribers = sub 但我有这个错误: 解决方法
ManyToMany经理假设您这样做
tour.subscribers = sub sub是订阅者的序列(元组,列表,查询集),而不是单个对象.然后这样做与完成相同: tour.subscribers.add(*sub) 由于sub不是一个序列,它会抛出这样的错误.我建议先保存然后再添加.我认为它也更具可读性,但可能只是我的观点: sub = Subscribers() tour = Tour() tour.id = "1" tour.name = "hello" tour.owner_id = user1 tour.save() tour.subscribers.add(sub) 希望这可以帮助 :) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |