使用tastype从外键检索数据

2024-09-27 21:33:08 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的Django应用程序中有两个模型:

型号.py

class Posts(models.Model):
    title = models.CharField(max_length=200, blank=True)
    author = models.ForeignKey(user,on_delete=models.CASCADE,default=None, blank=True)
    content = models.TextField()

class Unposted(models.Model):
    article = models.ForeignKey(Posts, on_delete=models.CASCADE)
    upload_at = models.DateTimeField(default=datetime.now, blank=True)

我正在尝试使用对Unposted的API请求从Posts检索数据。 这是我目前所拥有的,但我不确定如何从Posts模型获取数据。现在我只得到一个只有upload_at字段的JSON响应

资源.py

class UnpostedResource(ModelResource):
    class Meta:
        queryset = Unposted.objects.all()
        resource_name = 'unposted'

Tags: py模型truedefaultmodelonmodelsdelete
2条回答

如果我没说错的话,你可以直接导入你的Posts模型,然后通过for循环生成一个带有Posts模型的数组,使用foreign key from unposted来过滤你的Posts=)听起来很奇怪,我不确定是否有效,但看起来很不错。它看起来像:

queryset = Posts.objects.filter(article_in=[get(i.article) for i in Unposted.objects.all()])

在这种情况下,PostsUnposted的foreignkey,因此您需要在资源中为模型中相应的字段定义foreignkey字段,this tutorial可能会对您有所帮助

相关问题 更多 >

    热门问题