简体   繁体   English

将SQL请求转换为Django

[英]Translating SQL request to django

I am trying to create a request(in django) that will return an array of posts(only user's posts, which the current user in following). 我正在尝试创建一个请求(在django中),该请求将返回一组帖子(仅用户的帖子,当前用户在其后)。 Here are my models 这是我的模特

Posts: 帖子:

class Post(models.Model):
      title = models.CharField("Headline", max_length=100)
      body = models.TextField(max_length=1000)
      user_id = models.ForeignKey(User)
      thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
      timestamp = models.DateTimeField(auto_now_add=True)

Following/followers: 下面的追随者:

class FollowUser(models.Model):
      who_id = models.IntegerField()
      whom_id = models.IntegerField()
      timestamp = models.DateTimeField(auto_now_add=True)

Users: 使用者:

class UserProfile(models.Model):
      user = models.OneToOneField(User, unique=True)
      profile_pic = models.FileField(upload_to=get_upload_file_u_name, default='default.png', blank=True)
      bio = models.TextField(null=True)
      website = models.CharField(blank=True, max_length=100)
      location = models.CharField(blank=True, max_length=100)

      def __unicode__(self):
           return "%s's profile" % self.user

SQL request that I've created: 我创建的SQL请求:

     SELECT *  FROM POSTS Where user_id IN (select whom_id from FOLLOWERS Where user_id = 1 )

So, I've tried to translate this sql code to django-like but I wasn't able. 因此,我试图将此sql代码转换为类似django的代码,但我无法执行。 The main problem is that i can't request for an array. 主要问题是我无法请求数组。

Need help! 需要帮忙! Thanks 谢谢

Table names are automatically generated by combining the name of the app and the lowercase name of the model. 表名称是通过将应用程序名称和模型的小写字母组合而自动生成的。 Try to use <appname>_posts 尝试使用<appname>_posts

Try this 尝试这个

Post.objects.filter(user_id__in=FollowUser.objects.filter(who_id=1).values_list('whom_id'))

You can use this in your views.py by using the request parameter 您可以使用request参数在views.py使用它

Post.objects.filter(user_id__in=FollowUser.objects.filter(who_id=request.user.id).values_list('whom_id'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM