2017-04-23 123 views
0

我有2個表格。他們加入了一個外鍵關係。在Django,我該怎麼做我使用serializers.serialize,因此values()型號不起作用的django sql翻譯

select col1,col2,col3, table2.* from table1 join table2 on table1.table1id = table2.table2id 

相當於

編輯

這裏是我的2個型號我使用

class UserProfile(models.Model): 

    FbookID = models.CharField(
     max_length=100, 
     blank=True, 
     verbose_name="facebookid", 
     primary_key=True 
    ) 

    Fname = models.CharField(
     max_length=100, 
     blank=True, 
     verbose_name="fname" 
    ) 
    profilePic = models.CharField(
     max_length=256, 
     blank=True, 
     verbose_name="picture" 
    ) 
    Sname = models.CharField(
     max_length=100, 
     blank=True, 

    ) 
    faccesskey = models.CharField(
     max_length=255, 
     blank=True, 

    ) 
    userGender = models.CharField(
     max_length=15, 
     default='MALE') 

    joined = models.DateTimeField(
     auto_now_add=True, 
     verbose_name = "userjoinedsite" 
    ) 
    last_active = models.DateTimeField(
     auto_now=True, 
     verbose_name = "lastActiveOnSite" 
    ) 

    #have to refer to other class in strings as this table is not created when this command is run 
    last_loc = models.ForeignKey('user_LocLat',null=True) 
    email = models.EmailField(verbose_name="EmailOfUser") 


class user_LocLat(models.Model): 

    locationID = models.AutoField(
     verbose_name="location", 
     null= False, 
     primary_key = True 
    ) 
    FbookIDlat = models.ForeignKey('UserProfile') 
    Date_of_loc = models.DateTimeField(
     auto_now_add=True 
    ) 
    loc = models.PointField(
     verbose_name="location", 
     blank=False, 
     null=False 
    ) 
    speed = models.FloatField(verbose_name ='speedms',null=True) 

我需要從UserProfileloc和訪問從User_latloc.最主要的是我不能包括在返回

+0

請將您的django模型添加到問題 – aliva

+0

我更新我的問題以包含模型,謝謝 – bpb101

回答

0

您的SQL faccesskey沒有where條款,所以要選擇所有ocurrences:

user_loclat = user_LocLat.objects.all() 

然後你就可以遍歷和獲取到田間地頭,如:

for user_l in user_loclat: 
    loc = user_l.loc 
    Fname = user_l.FbookIDlat.Fname 
    ... 

或者你可以使用值():

users_data = user_LocLat.objects.all().values(loc, FbookDlat__Fname, ...) 
0
使用Django時,有沒有必要直接使用SQL(你可能需要一些特殊的情況下),但一般Django的ORM是最好的選擇

:你的代碼更改

FbookIDlat = models.ForeignKey('UserProfile') 

這個簡單

FbookIDlat = models.ForeignKey('UserProfile', related_name='fbookidlats') 

和刪除此行:

last_loc = models.ForeignKey('user_LocLat',null=True) 

當你創建一個外鍵的Django處理反向回撥

假設你想獲取信息的一個配置文件:

profile = UserProfile.objects.get(FbookID='fbid') 
    for fbookidlat in profile.fbookidlats.all(): 
     print(fbooidlat.speed) 

PS-1:請閱讀pep8它可以幫助你寫一個更乾淨的代碼

PS-2:請閱讀this鏈接