python - Fastest way to combine two models by attribute in Django -



python - Fastest way to combine two models by attribute in Django -

i have 2 models have attribute in common, 2 combine them if attributes in both equal, each 1 fetches info different databases:

first model class user(models.model): matricula = models.charfield(max_length=100) def __unicode__(self): homecoming self.matricula second model class usermoodle(models.model): matricula = models.charfield(max_length=100) def __unicode__(self): homecoming self.matricula example

if have:

lists_users = [<user: 123>, <user: 2345>,<user:567>] lists_users_moodle = [<usermoodle:123>, <usermoodle:2345>, <usermoodle:897>]

i combine them , result:

combined_models_lists = [[<user: 123>, <usermoodle: 123>], [<user: 2345>, <usermoodle: 2345>], [<user: 567>, none],[none, <usermoodle: 897>]]

thanks in advance!

one way create dicts lists(or queryset) first , iterate on union of keys of dicts desired output:

dict_users = {x.matricula : x x in lists_users} dict_moodle = {x.matricula : x x in lists_users_moodle} combined_models_lists = [[dict_users.get(x), dict_moodle.get(x)] x in set(dict_users).union(dict_moodle)]

another way iterate on sorted version of each queryset , population list, way utilize lesser memory compared above method:

users = user.objects.all().order_by('matricula') #order field `matricula` moodles = usermoodle.objects.all().order_by('matricula') out = [] it1 = iter(users) it2 = iter(moodles) prev1 = next(it1) prev2 = next(it2) while true: if prev1.matricula == prev2.matricula: out.append([prev1, prev2]) try: prev1 = next(it1) prev2 = next(it2) except stopiteration: out.extend([x, none] x in it1) out.extend([none, x] x in it2) break if prev1.matricula < prev2.matricula : out.append([prev1, none]) try: prev1 = next(it1) except stopiteration: out.append([none, prev2]) out.extend([none, x] x in it2) break if prev1.matricula > prev2.matricula : out.append([none, prev2]) try: prev2 = next(it2) except stopiteration: out.extend([prev1, none]) out.extend([x, none] x in it1) break

python django performance

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -