简体   繁体   中英

Connect 3 models in Django to access other model data

I have 3 models and in the 3rd model called Bookauth contains Foreign key for other two models Books, Authors. I want to get all the fields from 'Books' of a particular author(considering he wrote more then one book). I used manager in models but failed.

Models

class Authors(models.Model):
    aid = models.AutoField(primary_key=True)
    aname = models.CharField(max_length=200, blank=True, null=True)
    adescription = models.TextField( blank=True, null=True)

    def __str__(self):
        return self.aname


class Books(models.Model):
    bid = models.BigIntegerField(primary_key=True)
    bname = models.CharField(max_length=200, blank=True, null=True)
    bdescription = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.bname


class Bookauth(models.Model):
    bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True)
    aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True)

Views Don't think this is relevent

def getObject(request):
    all_books = Books.objects.all()
    html = serializers.serialize('json', all_books)
    return HttpResponse(html)
    #data = serializers.serialize("json", Books.objects.all())
    #return HttpResponse(data, mimetype='application/json')

def getAuth(request):
    all_auth = Authors.objects.all()
    htm = serializers.serialize('json', all_auth)
    return HttpResponse(htm)

def bookAuth(request):
    all_keys = Bookauth.objects.all()
    key_serial = serializers.serialize('json', all_keys)
    return HttpResponse(key_serial)

def book_search(request):
    b = request.GET.get('book', '')
    book = Books.objects.filter(pk = b)

    return HttpResponse(book)

def author_search(request):
    x = request.GET.get('author', '')
    auth = Authors.objects.filter(pk= x)


    return HttpResponse(auth)

Any suggestions on what I can do?

something like this:

 class Author(models.Model):
    aid = models.AutoField(primary_key=True)
    aname = models.CharField(max_length=200, blank=True, null=True)
    adescription = models.TextField( blank=True, null=True)
    books = models.ManyToManyField(Books)

    def __str__(self):
       return self.aname

Considering you are using intermediate table for ManyToMany relationship use ManyToManyField.through_fields on Author or Book model

Also useful for further queriing ManytoMany ORM examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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