Logic1
Logic1

Reputation: 1847

How to replace certain values in a queryset with Django?

i have these two models:

class Rfid(models.Model):
    id = models.IntegerField(primary_key=True)
    tag_id = models.CharField(db_column='Tag_ID', max_length=16, blank=True) # Field name made$
    site_id = models.CharField(db_column='Site_ID', max_length=8, blank=True) # Field name mad$
    time = models.IntegerField(db_column='Time', blank=True, null=True) # Field name made lowe$
    class Meta:
        managed = False
        db_table = 'RFID'

class RfidNames(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=24, blank=True)
    badge_id = models.CharField(max_length=16, blank=True)
    class Meta:
        managed = False
        db_table = 'RFID_names'

and in views i have this:

def rfid_lister(request):
    raw_scans = Rfid.objects.all().using('devices').order_by('-time')
    rfid_scan_list = list(raw_scans )

    return render_to_response("RFID_display.html",
                              locals(),
                              context_instance=RequestContext(request))

in my template im just displaying the data from raw_scan which looks like this:

A11     8400340910  8/20/2014 15:37:22
A11     8400340910  8/20/2014 13:55:10
A11     8400340910  8/20/2014 13:51:53
A11     8400340910  8/20/2014 13:43:33
A11     35021E05AE  8/20/2014 13:39:58
A11     0500679CF9  8/20/2014 13:39:26
A11     0500679CF9  8/20/2014 13:39:24 

however in the RfidNames table i have something like this:

name=bob, badge_id=8400340910

what im looking for is a way to render something that looks like this:

A11     bob         8/20/2014 15:37:22
A11     bob         8/20/2014 13:55:10
A11     bob         8/20/2014 13:51:53
A11     bob         8/20/2014 13:43:33
A11     35021E05AE  8/20/2014 13:39:58
A11     0500679CF9  8/20/2014 13:39:26
A11     0500679CF9  8/20/2014 13:39:24 

any ideas on how this could be done using a queryset?

thanks

Upvotes: 0

Views: 1345

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

It seems that Rfid.tag_id is really a foreign key to RfidNames.badge_id. You should declare it as such: a foreign key field can just as easily be a char field.

class Rfid(models.Model):
    ...
    tag = models.ForeignKey('RfidNames', db_column='Tag_ID', to_field='badge_id', blank=True, null=True)

Now you can simply follow the relationship in the template:

{% for scan in scan_list %}
    {{ scan.site_id }}  {{ scan.tag.name }}  {{ scan.time }}
{% endfor %}

That incurs a db lookup per row, so you can use select_related in the view to make it significantly more efficient:

scan_list = Rfid.objects.all().using('devices').order_by('-time').select_related('RfidNames')

Note you don't need the explicit step of converting to a list, in any case.

Upvotes: 1

Related Questions