How to add model with multiple services and prices for them in Python/Django

Viewed 111

I've just started learning Python/Django and I have a question for you guys:) I want to create a model in Django that will allow me to create a service with prices for each user.

For example, Users can open a form that will allow them to put there their services, and prices for each services.

But I don't know how to create an appropriate model. Please help.

1 Answers

You can define a model that links to the service and to the user that contains the price, so:

from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models

class Service(models.Model):
    service_name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.service_name

class ServicePrice(models.Model):
    service = models.ForeignKey(
        Service,
        on_delete=models.CASCADE
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )
    price = models.DecimalField(max_digits=9, decimal_places=2)

    def clean(self):
        duplicate = ServicePrice.objects.exclude(pk=self.pk).filter(
            user_id=self.user_id, service_id=self.service_id
        ).exists()
        if duplicate:
            raise ValidationError('The price for this service with this user already exists')
        return super().clean()

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['service', 'user'], name='price_per_user_service')
        ]

Here we thus refer to the Service model to specify for what service we record data, and to the user model to specify how much the service costs if done by that user. The uniqness constraint will enforce that there can not be two (or more) ServicePrices for the same service and user.

Related