pythondjangodjango-modelsdjango-forms

Can non-displayed fields of a Django model be altered during custom form validation but before committing model's data?


for the last few weeks I've been working on my first Django project: a database to register all incoming orders from Customers for a generic enterprise. Let's assume that each one of the sale reps could be assigned to a specific Customer for a whole natural year and assignments may vary from one year to another (i.e. agent A assigned to customer A in 2024, whereas in 2025, agent B might be in charge of customer A).

As a start, I decided to use a FK inside Orders model to refer to the associated Product and Customer. At the same time, the Assignments model would also keep a couple of FK to the Customer and Agent tables, so everything could be connected, accessible and data loops were avoided in my relational diagram. Still, this solution was really painful to get some data, specially when I needed to retrieve filtered data for the final templates... so I decided to turn everything upside down and take a different approach:

class Order (models.Model):
    assignment = models.ForeignKey("Assignment", on_delete=models.RESTRICT)
    product = models.ForeignKey("Product", on_delete=models.RESTRICT)
    quantity = models.PositiveIntegerField(default=1)
    order_date = models.DateField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

class Assignment (models.Model):
    assignment_year = models.PositiveSmallIntegerField()
    customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
    agent = models.ForeignKey("Agent", on_delete=models.CASCADE)
        
    class Meta:
        constraints = [
            UniqueConstraint(
                fields=['year', 'customer'], name='Primary_Key_Assignment'
            )
        ]
        
class Customer (models.Model):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=64)
    city = models.CharField(max_length=32)
    working_time_start = models.TimeField(blank=True, null=True)
    working_time_end = models.TimeField(blank=True, null=True)
    
    class Meta:
        verbose_name_plural = "Customers"
        constraints = [
            CheckConstraint(
                check = Q(working_time_start__isnull=True, working_time_end__isnull=True)|Q(working_time_start__isnull=False, working_time_end__isnull=False, working_time_start__lte=F('working_time_end')),
                name = 'Wrong working time limits',
            ),
        ]

So Orders are now directly referencing a specific assignments, which I admit it has some pros and cons and I'm not completely confortable with the fact of having the assignment's year and the order's date messing around in the same table due to redundancies and potential inconsistencies.

Once said this, I prefer to hide all this tricky details to the user and would like to have an admin view for the Orders which could hide the assignment FK field, but still would allow the user to select a Customer id. Afterwards, I would pick the Customer's id, the year based on the order's date and build up a valid assignment FK before the register could be saved into the database.

Something like the following:

from django.contrib import admin
from django.db.models import F, CharField
from django import forms
from django.db import models
from .models import Customer, Agent, Product, Order, Assignment

class OrderForm(forms.ModelForm):
    
    customers_list = forms.ModelChoiceField(queryset = Customer.objects.all())
    
    def clean(self):
        cleaned_data = self.cleaned_data
        
        form_date = cleaned_data['order_date']
        customer_form = cleaned_data['customers_list']
        cleaned_data['assignment'] = Assignment.objects.get(assignment_year=form_date.year, customer=customer_form.id)
        
        super(OrderForm, self).clean()

        return cleaned_data
    
    class Meta:
        model = Order
        fields = '__all__'

class OrderAdmin(admin.ModelAdmin):
    form = OrderForm
    fieldsets = (
      ('None', {
          'fields': ( 'customers_list', 'product', 'quantity', 'order_date', 'price', )
      }),
    )

admin.site.register(Order, OrderAdmin)

The clean method presented above complains because I am not including the assignment FK in the form, so I cannot modify it before starting validations at model's level (e.g. CheckConstraints, model's customized clean and save method, if any, etc.).

So my question is: is there any way I could possibly build a valid Order model based on inputs retrieved from the custom Order's form and append my pending assignment as a valid FK before the register is inserted into the database, even when no assignment is displayed to the user?


Solution

  • Pedantry incoming: opinions are plentiful, but clean() is IMO not the place for this logic. I'm going to use save() instead, as I find it makes more logical sense. You can rewrite it for clean() if you like, however.

    from django.utils import timezone
    
    class OrderForm(forms.ModelForm):
        customers_list = forms.ModelChoiceField(queryset = Customer.objects.all())
    
        class Meta:
            model = Order
            exclude = (
                'assignment', # Exclude `assignment` to avoid form validation errors
            )
    
        def save(self, commit=True):
            # Create an instance of type Order, but don't commit it to db (yet)
            # This can be easier to work with than form data
            obj: Order = super().save(commit=False)
    
            # Find or create the assignment
            assignment, _ = Assignment.objects.get_or_create(
                customer=obj.customer, 
                assignment_year=timezone.now().year
            )
    
            # Add the Order -> Assignment relationship and save the Order instance
            obj.assignment = assignment
            obj.save()
    
            return obj