Hello Everyone:

  I am trying my luck with django again, and I found a way to show a
list of related objects in a many-to-many relationship, using the
following model and view:

Model

# Flight Frequency
class Frequency(models.Model):

    day_translated = {'Sa': 'Saturday', 'Su': 'Sunday', 'Mo': 'Monday',
'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday'}

    days = models.CharField('Frequency', maxlength=2)

    def __str__(self):
        return self.day_translated[self.days];



# Flight Schedule

class Schedule(models.Model):
    flightNumber = models.CharField('Flight', maxlength=20)
    from_city = models.ForeignKey(Destination, related_name='From',
verbose_name='Origin')
    to_city   = models.ForeignKey(Destination, related_name='To',
verbose_name='Destination')
    airline   = models.ForeignKey(Airline)
    departs   = models.TimeField(help_text='All times are local')
    arrives   = models.TimeField(help_text='All times are local')
    from_date = models.DateField('Valid From', blank=True, null=True)
    till_date = models.DateField('Valid Till', blank=True, null=True)

    freq =
models.ManyToManyField(Frequency,filter_interface=models.HORIZONTAL,
verbose_name='Occurance')

    def __str__(self):
        return 'Flight '+self.flightNumber

    class Admin:
        list_display = ('flightNumber','from_city','to_city','airline',
'departs', 'arrives')
        list_filter = ['freq','from_city','to_city',
'departs','arrives']
        search_fields = ['from_city','to_city','freq']

View:

def index(request):
    flight_list = Schedule.objects.all().order_by('-departs')
    output = '<table border="0"
width="50%"><tr><td>Flight</td><td>Airline</td><td>Frequency</td></tr>'

    for fl in flight_list:
        output = output + '<tr><td>' + fl.flightNumber + '</td><td>'
        output = output + fl.airline.aname + '</td><td>'
        foo = fl.freq.all().values()
        for x in foo:
            output = output + ' ' + x['days']
        output = output + '</td></tr>'
    output = output + '</table>'
    return HttpResponse(output)


Now this does work, but is there a better way to get the same result?
The way I did it seems a bit of a hack.

Thanks


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to