Validating m2m relationship

I ended up restricting the queryset of the PrimaryKeyRelatedField in my serializer for AnswerToQuestion. This doesn’t stop assigning wrong choices “everywhere”, but at least prevents user from doing so when interacting with the API.

In the __init__ method of the serializer, after doing some manipulation of the kwargs passed to the field, I now do this, exploiting the fact that model serializers are (sometimes) passed the model instance as first argument:

try:
    answer_to_question_instance = args[0]
except:
    # DRF sometimes seems to call serializers spuriously without passing instance
    answer_to_question_instance = None
  
selected_choices_kwargs["queryset"] = (
    Choice.objects.all()
    if answer_to_question_instance is None
    else Choice.objects.filter(
        question_id=answer_to_question_instance.question_id
    )
)

This is then passed as an argument to fields['selected_choices'].