TypeError:*之后的add()参数必须是序列,而不是订阅者

时间:2012-11-27 02:05:17

标签: django django-models typeerror

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','m@m.com','m1')
user4= User.objects.create_user('lalal','m@m.com','m1')
sub = Subscribers()
tour = Tour()
tour.id = "1"
tour.name = "hello"
tour.owner_id = user1
tour.subscribers = sub

但我有这个错误: TypeError:*之后的add()参数必须是序列,而不是订阅者

1 个答案:

答案 0 :(得分:1)

ManyToMany经理假设您执行

tour.subscribers = sub

subSubscribers的序列(元组,列表,查询集),而不是单个对象。然后这样做与完成相同:

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)

希望这会有所帮助:)