Django休息框架获得一对多的关系数据

时间:2017-02-06 12:03:07

标签: django django-models django-rest-framework django-serializer

我有一个名为Event的django模型,它引用了Customer模型。

event_name = models.CharField(max_length=200, unique=True)
customer = models.ForeignKey(customer_models.Customer, db_index=True,
    on_delete=models.SET_NULL,
    related_name='customer_events', null=True)
event_location = models.CharField(max_length=200, default='')
event_date = models.DateField()

我需要获取客户列表以及API中每个用户的最新事件名称。

客户serializers.py文件是

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

客户views.py文件

class CustomerViewSet(viewsets.ModelViewSet):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

我该如何做到这一点?

1 个答案:

答案 0 :(得分:2)

var express = require("express"); var app = express(); var port = 54180; var BinaryServer = require('binaryjs').BinaryServer; var server = BinaryServer({ port: port }); app.listen(port, function () { console.log('server open on port ' + port); }); binaryServer = BinaryServer({ port: 9001 }); binaryServer.on('connection', function (client) { console.log('Binary Server connection started'); client.on('stream', function (stream, meta) { console.log('>>>Incoming audio stream'); var speech = require('@google-cloud/speech')({ projectId: 'MYPROJECT-1234' //keyFilename: '/config/KeyFile.json' }); const request = { config: { encoding: 'LINEAR16', sampleRate: 16000 }, singleUtterance: false, interimResults: true }; // Create a recognize stream const recognizeStream = speech.createRecognizeStream(request) .on('error', function (error) { console.log('Error'); console.log(error) }) .on('data', function (data) { console.log('Data'); console.log(data); }); // Send the microphone input to the Speech API stream.pipe(recognizeStream); stream.on('end', function () { fileWriter.end(); recognizeStream.end(); console.log('||| Audio stream ended'); }); }); }); 模型中,您可以使用Customer返回Customer实例的最新事件名称:

property

在序列化程序中,您可以为class Customer(models.Model): ... @property def latest_event_name(self): """Return latest event name.""" # self.customer_events.order_by('event_date').last() latest_event = self.customer_events.order_by('-event_date').first() return latest_event.event_name if latest_event else None 添加ReadOnlyField

latest_event_name