Django查询两个没有外键的表

时间:2018-03-23 07:37:27

标签: django django-models django-orm

你好我正在研究django。我有两本模特书籍和作者,但它们之间没有外键关系。

型号:

class Books(models.Model):
  bookid = models.IntegerField(primary_key=True)
  bookname = models.CharField(max_length=50)
  authorid = models.CharField(max_length=50)

  class Meta:
    managed = False
    db_table = 'books'

class Authors(models.Model):
  authorid = models.IntegerField(primary_key=True)
  authorname = models.CharField(max_length=50)


  class Meta:
    managed = False
    db_table = 'authors'

现在,我想根据作者姓名获取作者和相关书籍。

class Author_Books(generics.GenericAPIView):
def get(self, request, *args, **kwargs):
    try:
        authorname = 'Author Name'

        # filtering authors

        authors = Authors.objects.filter(authorname__icontains=authorname)

        # get author related books 

            How to acheive it without using raw sql query.


        return HttpResponse(authors)

    except Exception as err:
        return HttpResponse(err)

3 个答案:

答案 0 :(得分:0)

您可以使用以下查询。

for author in authors:
    books = Books.objects.filter(authorid = author.authorid )

注意:最好链接作者和books表。

答案 1 :(得分:0)

试试这个,

مرحبا



注意:您必须在两个表之间建立外键关系,这是最佳做法
示例

class Author_Books(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        try:
            authorname = 'Author Name'

            # Changes #
            auther_qryset = Authors.objects.filter(authorname__icontains=authorname)
            authorid_list = auther_qryset.values_list('authorid', flat=True)  # returns a 'list' contains `authorid`
            book_queryset = Books.objects.filter(authorid__in=authorid_list)
            # do something with "book_queryset"

            return HttpResponse(authors)
        except Exception as err:
            return HttpResponse(err)

答案 2 :(得分:0)

如果要使用一个SQL(连接两个表)从数据库中获取数据,则必须在模型中使用django ForeignKey,否则django后端将查询两次。 喜欢这个

author = Authors.objects.get(pk=1)
books = Books.objects.filter(authorid=author.id)

如果使用foreignkey

books = Books.objects.filter(foreignkey__authorname=authorname)