'DRF best way to get data for many to many fields for use in React form
I am not sure the best way to handle the following, all the ways i can think of would result in many database hits, or having to create quite a complex algorithm for something that I think would be a common use case potentially.
I have 2 models in question:
class ExperienceType(models.Model):
name = models.CharField(max_length=50, null=True)
answer_required = models.BooleanField(default=False)
class UserExperienceTypeAnswer(TimeStampedModel):
NA, NONE, SOME, LOTS, EXPERT = range(5)
ANSWER_CHOICES = {
(NA, "Not interested"),
(NONE, "None"),
(SOME, "Some"),
(LOTS, "Lots"),
(EXPERT, "Expert"),
}
user = models.ForeignKey(User)
exp_type = models.ForeignKey(RecruitmentExperienceType)
answer = models.PositiveSmallIntegerField(choices=ANSWER_CHOICES)
unique_together = ["user", "exp_type"]
I then have a form in react that loops through the ExperienceTypes returned, these are dynamic so can be many. For each type i have a Select that allows the user to select an experience level. I will then save (or update) that record in UserExperienceTypeAnswer.
The issues i have is:
- Best way to get the data so that on form load I can prefill the selects if user has given an answer previously.
Current thought process but not sure it is best:
- Get all ExperienceType records
- Get all UserExperienceTypeAnswer records related to that user
- When rendering the Select i should compared to see if answer exists and fill value if it has.
Maybe I have already thought of the best way, but as ive been looping through my head for a good few hours maybe someone can provide some further input?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
