Changing a foreign key on an object inside admin interface

Hi,

in my admin interface, I want to change a foreign key of a model from a dropdown. This foreign key is a part of composite primary key. However when I try to change the foreing key, django creates a new object, it doesn’t modify the existing one. Why is that happening and how can I change the foreign key of the current model. I’m using PostgreSQL on the backend.

Here is my model:

class CropStageHasCondition(models.Model, GenericCheckForDelete):
    id = CompositeKey(columns=['crop_stage_id', 'condition_id'])
    crop_stage = models.ForeignKey(CropStage, models.DO_NOTHING)
    condition = models.ForeignKey(Condition, models.DO_NOTHING)
    threshold_low = models.FloatField(blank=True, null=True)
    threshold_high = models.FloatField(blank=True, null=True)
    threshold_mismatch_impact = models.ForeignKey('ThresholdMismatchImpact', models.DO_NOTHING, blank=True, null=True)
    health_threshold_low = models.FloatField(blank=True, null=True)
    health_threshold_high = models.FloatField(blank=True, null=True)
    health_threshold_mismatch_impact = models.ForeignKey('ThresholdMismatchImpact', models.DO_NOTHING, related_name='cropstagehascondition_health_threshold_mismatch_impact_set', blank=True, null=True)
    relevant_for_calculation = models.BooleanField()

    class Meta:
        managed = False
        db_table = 'planner"."crop_stage_has_condition'
        unique_together = (('crop_stage', 'condition'),)

    def __str__(self) -> str:
        return f"{self.crop_stage} - {self.condition}"

    def clean(self):
        existing_objects = CropStageHasCondition.objects.filter(
            crop_stage=self.crop_stage,
            condition=self.condition
        )
        if existing_objects.exists():
            raise ValidationError({'crop_stage': "CropStageHasCondition with this crop_stage and condition already exists.",
                                   'condition': "CropStageHasCondition with this condition and crop_stage already exists."})

For composite key I’m using viewflow library.

Thanks for your help.

It’s happening because that’s how the ORM is designed and that’s how it’s documented. (See primary_key)

Also, I suggest you don’t try to use a composite primary key. There are reasons why Django doesn’t currently support this. It’s a very complex issue that has been hanging around for a long time.
See:

1 Like