django sql的翻译

时间:2017-04-23 00:49:20

标签: sql django models

我有2张桌子。他们加入了外键关系。在django中,我该如何做相同的

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

我正在使用serializers.serialize,因此values()不适用于模型

修改

以下是我正在使用的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)

我需要从Fname,Sname,Gender, last_active, emailUserProfile以及loc speed访问User_latloc.主要是我不能包含faccesskey回报

2 个答案:

答案 0 :(得分:0)

你的sql没有where子句,所以要选择所有的事件:

user_loclat = user_LocLat.objects.all()

然后您可以迭代并访问字段,例如:

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

或者你可以使用values():

users_data = user_LocLat.objects.all().values(loc, FbookDlat__Fname, ...)

答案 1 :(得分: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链接