8

I need to fetch columns from multiple tables, how do I achieve this?

UserLog


+------------+----------+------+-----+---------+----------------+
| Field      | Type     | Null | Key | Default | Extra          |
+------------+----------+------+-----+---------+----------------+
| log_id     | int(11)  | NO   | PRI | NULL    | auto_increment |
| time       | datetime | NO   |     | NULL    |                |
| ip_address | char(15) | YES  |     | NULL    |                |
| event_id   | int(11)  | NO   | MUL | NULL    |                |
| user_id    | int(11)  | NO   | MUL | NULL    |                |
+------------+----------+------+-----+---------+----------------+

Events


+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| event_id    | int(11)      | NO   | PRI | NULL    | auto_increment |
| description | varchar(200) | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+

This is my models.py

class Events(models.Model):
        event_id = models.AutoField(primary_key=True,verbose_name="Event id")
        description = models.CharField(max_length=200,verbose_name="Description")

        def __unicode__(self):
                return u"%d : %s" % (self.event_id, self.description)

class UserLog(models.Model):
        log_id = models.AutoField(primary_key = True)
        user = models.ForeignKey(User)
        event = models.ForeignKey(Events,verbose_name = "event")
        time = models.DateTimeField(default=datetime.now,blank=True)
        ip_address = models.IPAddressField(null=True)


        def __unicode__(self):
                return u"%s (%s): %s" % (self.log_id, self.user, self.event)

Spcifically I want to do SELECT log_id,time,user_id,event_id,description from UserLog,Events where UserLog.event_id = Events.event_id

I tried UserLog.objects.filter(event_id__event_id).values('log_id','time','user_id','event_id','description') . But it says no such fields.

Is there something I need to change in my models class?

2
  • Can you post your django model code? Commented Sep 29, 2014 at 22:57
  • Oops, that was supposed to be Events. Updated! Commented Sep 30, 2014 at 1:42

3 Answers 3

10

Try this:

UserLog.objects.filter(event_id=1).values('log_id', 
                                          'time',
                                          'user_id',
                                          'event_id', 
                                          'event__description')

Alternately, you could use select_related:

UserLog.objects.filter(event__id=1).select_related('event')

then you'll get UserLog objects, with the event pre-fetched, so you can access the event without triggering another query.

(Also, standard naming convention would be to call the model Event, not Events)

Sign up to request clarification or add additional context in comments.

1 Comment

That worked! Dumb enough, I forgot to access the other tables fields by foreignkey_fields. Thanks :)
3

use select_related() like this:

UserLog.objects.filter(event_id__event_id=1).select_related('event').values('log_id','time','user_id','event_id', 'event__description')

3 Comments

That was quick! I tried this UserLog.objects.filter(event_id__event_id=1).select_related('description').values() And i got [{'log_id': 4L, u'event_id': 1L, 'ip_address': u'10.100.32.142', u'user_id': 2L, 'time': datetime.datetime(2014, 9, 25, 21, 29, 28, tzinfo=<UTC>)} 'Description' field isn't being displayed!
You are right, I was trying to incorrectly access fields from other tables.
Guys could you please help me resolve this stackoverflow.com/questions/49587819/…
0
dataStudent =  Studentinfo.objects.select_related().values(
    'country__countryname',
    'state__statename', 
    'city__cityname',
    'id','studentname',
    'rollno',
    'email',
    'phoneno')

in the country__countryname country is the name of field when u define the relationship like follow

city =  models.ForeignKey(City, on_delete=models.CASCADE)
state =  models.ForeignKey(State, on_delete=models.CASCADE)
country =  models.ForeignKey(Country, on_delete=models.CASCADE)

and countryname is the table field inside the country table and
same as state__statename and city__cityname

and other fields are from Studentinfo model

so that will give me the following result

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.