假设我正在创建一个投票应用程序,我希望用户一起创建他们的投票和他们的选择,而不是在以后修改它们。
目前我有类似的东西:
class PollManager(models.Manager):
def create_poll(self, name, owner, choices):
new_poll = Poll(name=name, owner=owner)
new_poll.save()
for name in choices:
Choice(name=choice, poll=new_poll).save()
class Poll(models.Model):
name = models.CharField(max_length=30)
objects = PollManager()
class Choice(models.Model):
name = models.CharField(max_length=30)
poll = models.ForeignKey(Poll)
但是,如果Poll.objects.create_poll
方法的输入无效,例如,我最终可能会意外保存投票而没有任何选择。但我不认为我可以new_poll.save()
在创建 Choice 实例时不出错而离开到最后。
我可以在方法try...except
的开头放一些东西create_poll
来确保输入都是有效的,但我担心如果我这样做会破坏 DRY。
我应该以这种方式使用自定义管理器方法吗?如果是这样,我应该如何最好地处理验证?如果不是,对于某些等效功能,什么被认为是好的做法?
提前致谢。