A 对这一的延迟答复:您也可超越构件(_init__
):
class FollowerList(models.Model):
follower = models.ForeignKey(User,related_name="follower")
followed = models.ManyToManyField(User,related_name="followed"
def __init__(*args, followed=[], **kwargs):
super(FollowerList, self).__init__(*args, **kwargs)
self.save()
for user in followed:
self.followed.add(user)
ie here I ve explicitly handled the followed
keyword argument in the __init__
function, while passing all other args
and kwargs
on to the default constructor.
The call to save
makes sure that the object has been registered and can thus be used in an m2m relationship.
This then allows you to do create FollowerList
with one line, eg
flst = FollowerList(follower=user, followed=[user,])
Alternatively, as pointed out by Johannes, saving a model in the __init__
is not expected. The preferred approach would be to create a Manager
method - see here for details: https://docs.djangoproject.com/en/1.9/topics/db/managers/
and then to create a FollowerList
:
fl = FollowerList.objects.create(*args, followed, **kwargs)