How to deal with foreign keys from another microservice?
I have 2 microservices: one for subjects and one for questions. Don't ask me why. It has to be like that. So in questions I have this m2m-like model:
class QuestionsSubjects(models.Model):
question = models.ForeignKey(Question, ...)
subject_id = models.PositiveIntegerField()
And question model has this property:
@property
def subjects(self) -> QuerySet[int]:
return QuestionsSubjects.objects \
.filter(question=self).values_list('subject_id', flat=True)
I don't have Subject model I only have ids coming from frontend. I need to store relations between questions and subjects. But what I have now is not convenient because it's hard to create questions with subjects.
For example, I have this QuestionSerializer:
class QuestionSerializer(serializers.ModelSerializer):
subjects = serializers.ListField(child=serializers.IntegerField())
class Meta:
model = Question
fields = [
# some other question fields
'subjects',
]
def create(self, validated_data: dict[str, Any]) -> Question:
subject_ids: list[int] = validated_data.pop('subjects', [])
question = Question.objects.create(**validated_data)
create_questions_subjects(question, subject_ids)
return question
def update(self, question: Question, validated_data: dict[str, Any]) -> Question:
# delete all existing rows for specific question
QuestionsSubjects.objects.filter(question=question).delete()
# and recreate them with new subject ids
subject_ids: list[int] = validated_data.pop('subjects', [])
create_questions_subjects(question, subject_ids)
return super().update(question, validated_data)
The problem is I'm getting subject ids from client and everytime I need to go through each subject id and create row in QuestionsDirections for each subject with specific question. So I created function called create_questions_subjects:
def create_questions_subjects(
question: Question,
subject_ids: list[int]
) -> None:
questions_subjects_list: list[QuestionsSubjects] = []
for id in subject_ids:
questions_subjects_list.append(
QuestionsSubjects(question=question, subject_id=id)
)
QuestionsSubjects.objects.bulk_create(questions_subjects_list)
But I don't where I have to put it. It's still in serializers.py. It works but looking so ugly to me. Is there a better way of dealing with such a task?