2015-04-02 66 views
0

鉴于Django的1.8,Python的2.7.5,PostgreSQL和下面的通用模型比较两个相似字段:从两个不同的模型

class restAPI(models.Model): 
    rest_id = models.CharField(max_length=20) 
    rest_host = models.CharField(max_length=20) 
    rest_mode = models.CharField(max_length=20) 
    rest_state = models.CharField(max_length=20) 


class soapAPI(models.Model): 
    soap_id = models.CharField(max_length=20) 
    soap_host = models.CharField(max_length=20) 
    soap_asset = models.CharField(max_length=20) 
    soap_state = models.CharField(max_length=20) 

在一个完美的世界soapAPI.soap_hostrestAPI.rest_host将完美匹配。然而,情况很少。我正在尝试查找并返回soapAPI中不存在的任何主机,这些主机不在restAPI中。我有一个工作方法,目前我使用python解析这些数据,然后将它保存到它在django中的模型中,但我必须相信我可以使用模型本身来做到这一点(我认为这样做会更有效) 。

其中soapAPI.soap_hostrestAPI.rest_host使用利用.raw()由django的或提供的ORM丢失,优选地与ORM如何一个返回的soapAPI模型?任何和所有的帮助将不胜感激,因为这对我来说是一种学习体验。先谢谢你。

EDIT1

完全开放以及建模为某种形式的答案的关系。

EDIT2

离开开放的,因为我不得不相信这是一个更好的办法来做到这一点不是多个查询集。

EDIT3

此外,有没有办法做到muiltiple __in的什么?我实际上需要返回整个soapAPI模型,其中soapAPI.soap_host缺失restAPI.rest_hostsoapAPI.soap_state是'活'。

回答

0

这是我能想出给出的答案是@HassenPy给出最佳:

excludehosts = restAPI.objects.values_list('rest_host', flat=True) 
missinghosts = soapAPI.objects.exclude(soap_host__in=excludehosts) 

编辑

回答我的编辑3,这是我能想出的最好搭配:

excludehosts = restAPI.objects.values_list('rest_host', flat=True) 
missinghosts = soapAPI.objects.exclude(soap_host__in=excludehosts) 
missinghosts.filter(soap_state='Live') 

尽管下面的作品,以及:

excludehosts = restAPI.objects.values_list('rest_host', flat=True) 
soapAPI.objects.filter(soap_state='Live').exclude(soap_host__in=excludehosts) 

不确定哪一个在技术上更好,因为我不能真正辨别退货时间的差异,但嘿工作的解决方案。

0

应该是这样的:

rest_hosts = restAPI.objects.only("rest_host") 
excluded_rest_hosts = [host.rest_host for host in rest_hosts] 
missing_soap_hosts = soapAPI.objects.exclude(soap_host__in=excluded_rest_hosts) 

希望这有助于!

+0

无论出于何种原因,我得到这个:'FieldError:无法解析关键字'rest_host'到字段中。选择是:id,soap_asset,soap_host,soap_id,soap_state' – beardedeagle 2015-04-02 17:36:00

+0

找出它,并用较少的代码。看到我的答案。谢谢你让我开始,但你的帮助是有帮助的。现在如果我只能弄清楚如何在一个查询集中执行此操作。 – beardedeagle 2015-04-02 17:43:19

+0

我没有看到任何答案O.o – HassenPy 2015-04-02 17:44:29

相关问题