Django: apply "same parent" constraint to ManyToManyField mapping for itself

I have a model where tasks are parts of work, each of which may depend on a number of other tasks that need to be completed before it starts. Tasks are grouped into jobs, and I want to ban dependencies between tasks. This is the corresponding subset of my model:

class Job(models.Model):
    name = models.CharField(max_length=60, unique=True)

class Task(models.Model):
    job = models.ForeignKey(Job)
    prerequisites = models.ManyToManyField(
        'self',
        symmetrical=False,
        related_name="dependents",
        blank=True)

Is there any way to express the restriction that all the necessary tasks must have the same job? I could apply this at the presentation level, but I would really like to make it work at the model level, so that the administrator interface displays the appropriate parameters when choosing the necessary conditions for the task. I thought I could use "limit_choices_to", but upon closer inspection, it seems like a static query is required, and not something that depends on the values ​​in this task object.

+3
source share
1 answer

There are two separate issues here.

, "" save() ( Task.save(), M2M). Django 1.2 , .

, , . queryset ModelMultipleChoiceField init:

class TaskForm(forms.ModelForm):
   class Meta:
      model = Task

   def __init__(self, *args, **kwargs):
      super(TaskForm, self).__init__(*args, **kwargs)
      self.fields['prerequisites'].queryset = Task.objects.filter(job=self.instance.job)

, ( "self.instance.job", , None); , , .

+3

Source: https://habr.com/ru/post/1719502/


All Articles