0

I'm creating a website about services provided by certain professionals. Each professional creates his own personal page and lists services which he provides, with prices.

However, he has a certain limited choice of service types to choose from. The professional can't create new service types — it's admin's prerogative. Each service that the professional lists has to be of a certain pre-determined type, and he can't have to services of the same type.

So far, that's what I have in models.py:

# Created and edited only by site administration
class Service(models.Model):
    url_name = models.CharField(max_length=100, primary_key=True) # to use in URLs
    name = models.CharField(max_length=200)
    description = models.TextField()

    def __unicode__(self):
        return self.name

class Master(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()

    def __unicode__(self):
        return self.name

class MasterService(models.Model):
    master = models.ForeignKey(Master)
    service = models.ForeignKey(Service)
    price = models.PositiveIntegerField(blank=True)

How can I edit that model in such a way that the django will "know" that each master can only have 1 service of a certain Service type?

Max Yankov
  • 12,551
  • 12
  • 67
  • 135
  • I think this is what you're looking for: http://stackoverflow.com/questions/232435/how-do-i-restrict-foreign-keys-choices-to-related-objects-only-in-django – Paul Aug 27 '13 at 01:19

1 Answers1

1

Try unique_together.

class MasterService(models.Model):
    master = models.ForeignKey(Master)
    service = models.ForeignKey(Service)
    price = models.PositiveIntegerField(blank=True)

    class Meta:
        unique_together = ('master', 'service')

This constraint will be enforced at the database level, so it won't be possible to associate a service with a master more than once. See the docs.

Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102