我正在尝试使用JSON字段以一种简单的方式来管理一些翻译。
翻译需要可排序和可过滤。
给出以下模型:
class Alarm(models.Model):
name = models.CharField(max_length=256, unique=True)
value = models.BooleanField()
name_translations = JSONField(null=True, blank=True, default={})
created_at = models.DateTimeField(editable=False)
class HistoryAlarm(models.Model):
alarm = models.ForeignKey(Alarm, on_delete=models.CASCADE)
value = models.BooleanField()
created_at = models.DateTimeField(editable=False)
我可以执行以下操作:
alarm_list = Alarm.objects.all().annotate(
translated_name=KeyTextTransform('en-US', 'name_translations')
)
alarm_list[0].translated_name
> "Translation alarm 0"
alarm_list = Alarm.objects.all().annotate(
translated_name=KeyTextTransform('it-IT', 'name_translations')
)
alarm_list[0].translated_name
> "Traduzione allarme 0"
我将如何编写查询集,以便做到这一点?
history_alarm_list = ???
history_alarm_list[0].alarm.translated_name
> "Traduzione allarme 0"
到目前为止,我得到的是这个,但是它将translated_name
绑定到了history_alarm,而不是警报:
history_alarm_list = HistoryAlarm.objects.annotate(
translated_name=KeyTextTransform('it-IT', 'alarm__name_translations')
)
history_alarm_list[0].translated_name
> "Traduzione allarme 0"
之所以需要这样做是因为:
translated_name
,则在序列化HistoryAlarms记录时也必须在其中。 class AlarmSerializer(serializers.ModelSerializer):
translated_name = serializers.SerializerMethodField()
def get_translated_name(self, obj):
return obj.translated_name
class Meta:
model = Alarm
fields = '__all__'
class HistoryAlarmSerializer(serializers.ModelSerializer):
alarm = AlarmSerializer(read_only=True)
class Meta:
model = HistoryAlarm
fields = '__all__'