I have two models. sitesubnets and devicesubnets.
I would like to compare the two models so I can create two lists. one list will have matching subnets one will have non matching subnets across them
I have tried using set difference but as they are different models I don think it works
test queries:
sitesubnet_data = SiteSubnets.objects.filter(site_id=site_id)
devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id)
data = set(sitesubnet_data).difference(set(devicesubnet_data))
when I compare sitesubnet_data with data, they are the same
my models:
class SiteSubnets(models.Model):
site = models.ForeignKey(SiteData, on_delete=models.CASCADE)
subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE)
class Meta:
verbose_name = "Site Subnets"
verbose_name_plural = "Site Subnets"
unique_together = ('site', 'subnet',)
class DeviceSubnets(models.Model):
device = models.ForeignKey(DeviceData, on_delete=models.CASCADE)
subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE)
class Meta:
verbose_name = "Device Subnets"
verbose_name_plural = "Device Subnets"
unique_together = ('device', 'subnet',)
As far as I know, we could only compare same class objects (model objects). So, You should generate two different queryset of Subnets
class which is common to both models. So I found one possible solution for your question, which is
devicesubnet = Subnets.objects.filter(devicesubnets__device_id=device_id)
sitesubnet = Subnets.objects.filter(sitesubnets__site_id=site_id)
common_subnets = list(set(devicesubnet) & set(sitesubnet))
Here common_subnets
will hold the result, which has common Subnets
instances with both SiteSubnets
model and DeviceSubnets
model
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.