I have two models and I want to find out the common sets of values on the basis of their ids
First model:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
# WE ARE AT MODELS/UNIVERSITIES
class Universities(models.Model):
id = models.IntegerField(db_column="id", max_length=11, help_text="")
name = models.CharField(db_column="name", max_length=255, help_text="")
abbreviation = models.CharField(db_column="abbreviation", max_length=255, help_text="")
address = models.CharField(db_column="address", max_length=255, help_text="")
status = models.BooleanField(db_column="status", default=False, help_text="")
createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="")
modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="")
updatedBy = models.ForeignKey(User,db_column="updatedBy",help_text="Logged in user updated by ......")
class Meta:
managed = False
get_latest_by = 'createdAt'
db_table = 'universities'
And the other model:
from __future__ import unicode_literals
from django.db import models
class NewsUniversityMappings(models.Model):
id = models.IntegerField(db_column="id", max_length=11, help_text="")
newsMappingId = models.IntegerField( db_column='newsMappingId' ,max_length=11, help_text="")
universityId = models.IntegerField( db_column='universityId', max_length=11, help_text="")
createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="")
class Meta:
managed = False
db_table = 'news_university_mappings'
Now, in my views, i have created objects for both models:
def add_promoter_news(request, mapping_id=None, news_virtual_id=None):
try:
university_all_list = Universities.objects.using("cms").all
published_university_list = NewsUniversityMappings.objects.using("cms").filter(newsMappingId=news_virtual_id).all()
I want to find the common of both the models on the basis of in of Universities model and universityId of NewsUniversityMappings model.Any help would be appreciated.
Thanks in advance
Well, I'm not sure if this is what you want, but:
def add_promoter_news(request, mapping_id=None, news_virtual_id=None):
try:
# Get that queryset
published_university_list = NewsUniversityMappings.objects.using("cms").filter(newsMappingId=news_virtual_id).all()
# Get list of distinct universityIds
published_university_IDS_list = published_university_list.values_list('universityId',flat=True).distinct()
# Get queryset of all Universities
university_all_list = Universities.objects.using("cms").all()
# Get queryset of universities with ids on previous list
university_list = university_all_list.filter(id__in=published_university_IDS_list)
Now in university_list you have only Universities with ID, that was somewhere in universityId variable of at least one of NewsUniversityMappings.
Is that it?