Let's say I'm creating a polls app, and I want users to create their polls and their choices together, and not modify them at a later point.
At the moment I have something like:
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)
However, if the input to the Poll.objects.create_poll
method isn't valid, I might end up accidentally saving a poll without any choices, for example. But I don't think I can leave new_poll.save()
until the end without getting errors when creating the Choice instances.
I can put some try...except
stuff at the start of the create_poll
method to make sure the input is all valid, but I'm concerned I'll be breaking DRY if I do this.
Should I be using a custom manager method in this way? If so, how should I best deal with validation? If not, what's considered to be good practice for some equivalent functionality?
Thanks in advance.