我正在将我的Python迁移到REST API,我正在使用Django框架1.8。 我按照教程,我的一个请求是插入一个取决于几个fk的对象(服务器)。在我的Python应用程序中,我通常有3个查询来插入记录,使用 RETURNING id 来存储FK的ID,最后使用1个查询来插入我的Server对象。我怎样才能在Django中实现这一目标? 这些是我的模型和序列化器:
serializers.py
#Server Serializer
class ServerSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Server
fields = ('id', 'owner', 'discovered', 'status', 'serialnumber', 'hostname', 'description', 'created')
models.py
class Server(models.Model):
owner = models.ForeignKey('auth.User', related_name='server')
discovered = models.BooleanField(default=False)
status = models.SmallIntegerField(default=0)
serialnumber = models.CharField(max_length=100, null=True)
hostname = models.CharField(max_length=250)
description = models.CharField(max_length=250, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
fk_server_model = models.ForeignKey('ServerModel', db_column='fk_server_model')
fk_licensing = models.ForeignKey(Licensing, db_column='fk_licensing', blank=True, null=True)
fk_network_services = models.ForeignKey(NetworkServices, db_column='fk_network_services', blank=True, null=True)
fk_network_interfaces = models.ForeignKey(NetworkInterfaces, db_column='fk_network_interfaces', blank=True, null=True)
fk_server_credentials = models.ForeignKey('ServerCredentials', db_column='fk_server_credentials', blank=True, null=True)
def save(self, *args, **kwargs):
super(Server, self).save(*args, **kwargs)
class Meta:
managed = False
db_table = 'server'