tags:

views:

64

answers:

1

Hello.

I have 2 different tables in my database. They have some variables common and some different. For example:

Table1:

  • ID
  • Date
  • Name
  • Address
  • Fax

Table2:

  • ID
  • Date
  • Name
  • e-mail
  • Telephone number

I want to display data together sorted by date & ID but from both tables. For example, first displayed will be the newest record from first table, but the second one will be the record from another table posted right after first one.

Hope everybody understand, sorry for my English.

Cheers.

A: 

Select entries from both models, than put them into a single list and sort them. Like that:

result = (list(first_query) + list(second_query))
result.sort(cmp=foo)
return result

where foo is a function, which is used to compare two elements:

def foo(a, b):
  if a.date > b.date:
    return 1
  if a.date < b.date:
    return -1
  if a.date == b.date:
    if a.id > b.id:
      return 1
    if a.id < b.id:
      return -1
    return 0

And the to display:

<table>
{% for object in result %}
  {{ object.render_table }}
{% endfor %}
</table>

and in models (just one table):

class Table1(models.Model):

  ..

  def render_table(self):
    return '<tr><td>table1</td></tr>'
gruszczy
Hmm, it returns none... querries aren't empty.
DJPython
You must be doing something wrong, because it would be an empty QuerySet, not None for empty table. You called it list(Table1.objects.all()) + list(Table2.objects.all())?
gruszczy
here is my code: my_list= (list(Table1.objects.all()) + list(Table2.objects.all())).sort(foo) - returns no errors but when I'm trying to display "my_list" in template, it returns None.
DJPython
Oh, you are right, sort doesn't return anything. It just sorts the table. I have modified the answer. Check this one.
gruszczy
I believe you need to add a `cmp = foo` in the `sort` call.
sykora
You are absolutely right :-)
gruszczy
But, one more question - how can I in template check, from which table comes record? I was trying "{% ifequal lista "Table1 object" %} do smth {% endifequal %}" but it doesn't work.
DJPython
I don't think checking from which table an object comes is the right way. If you want to render something specific for objects from different tables, add proper method to each model and call it. There some ways to check objects type, but that's not how object oriented programming works. And especially not in templates.
gruszczy
I want to display all data on the same page and by Table1 objets write "table1" and by Table2 "table2", so how can I do it? And why it is wrong?
DJPython
As I said, in model create render method, which will render an object in html (you can make many, like render_div or render_table, if you need to display this in many ways). I'll modify the answer to explain in a moment.
gruszczy