1024programmer Java Give an example to explain how the data model in Django accesses foreign key values.

Give an example to explain how the data model in Django accesses foreign key values.

First set up a data model about books:

 from django.db import models

 class Publisher(models.Model):
   name = models.CharField(max_length=30)
   address = models.CharField(max_length=50)
   city ​​= models.CharField(max_length=60)
   state_province = models.CharField(max_length=30)
   country = models.CharField(max_length=50)
   website = models.URLField()

   def __unicode__(self):
     return self.name

 class Author(models.Model):
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=40)
   email = models.EmailField()

   def __unicode__(self):
     return u'%s %s' % (self.first_name, self.last_name)

 class Book(models.Model):
   title = models.CharField(max_length=100)
   authors = models.ManyToManyField(Author)
   publisher = models.ForeignKey(Publisher)
   publication_date = models.DateField()

   def __unicode__(self):
     return self.title


Access foreign key value

When you get a ForeignKey field, you will get the related data model object. For example:

 >>> b = Book.objects.get(id=50)
 >>> b.publisher
 >>> b.publisher.website


For relationships defined with “ForeignKey“, the opposite end of the relationship can also be traced back, but it is slightly different due to asymmetry. To obtain books directly through a “publisher“ object, use publisher.book_set.all(), as follows:

 >>> p = Publisher.objects.get(name='Apress Publishing')
 >>> p.book_set.all()
 [, , ...]


Actually, book_set is just a QuerySet, so it can implement data filtering and splitting like QuerySet, for example:

 >>> p = Publisher.objects.get(name='Apress Publishing')
 >>> p.book_set.filter(name__icOntains='django')
 [, ]


The attribute name book_set is composed of the lower case of the model name (such as book) plus _set.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/787617

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us


Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top