In my posgresql I have a model "words":
class Words(models.Model):
word = models.CharField(db_index=True, max_length=50)
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
time_stamp = models.TimeField(auto_now=False, auto_now_add=False)
In my view, after a query, I search for words that icontains the query itself A lot of words are duplicated and i need to aggregate them in the result My goal is to respond with a json file that collects the various words and lists their timestamps Something like this:
[
{
"word": "foo",
"list":
[
{
"id": 10416,
"lesson": 11,
"time_stamp": "00:02:49.100000"
},
{
"id": 10702,
"lesson": 12,
"time_stamp": "00:27:31.300000"
},
...
]
},
{
"word": "too",
"list":
[
{
"id": 10416,
"lesson": 11,
"time_stamp": "00:02:49.100000"
},
{
"id": 10702,
"lesson": 12,
"time_stamp": "00:27:31.300000"
},
...
]
},
]
I found two solution but both with downside
1- rework the database like this:
class WordsName(models.Model):
word = models.CharField(unique=True, db_index=True, max_length=50)
class WordsDetail(models.Model):
wordName = models.ForeignKey(WordsName, on_delete=models.CASCADE)
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
time_stamp = models.TimeField(auto_now=False, auto_now_add=False)
but it's a big change
2- make another Serializer:
class WordListSerializer(serializers.ModelSerializer):
word = serializers.SerializerMethodField('get_word')
list = serializers.SerializerMethodField('list_word')
class Meta:
model = Words
fields = ['word', 'list']
def get_word(self, obj):
return obj.word + '*'
def list_word(self, obj):
word = Words.objects.filter(word=obj.word)
return BinomiSerializer(word, many=True).data
class WordSerializer(serializers.ModelSerializer):
class Meta:
model = Words
fields = ['id', 'lesson', 'time_stamp']
It works but i don't know if it is legal and it makes a lot of query to the db