Django의 Many-to-many 관계.

1010 단어
from django.db import models  
class Publication(models.Model):  
    title = models.CharField(max_length=30)  
    # On Python 3: def __str__(self):  
    def __unicode__(self):  
        return self.title  
    class Meta:  
        ordering = ('title',)  

class Article(models.Model):  
    headline = models.CharField(max_length=100)  
    publications = models.ManyToManyField(Publication)  
    # On Python 3: def __str__(self):  
    def __unicode__(self):  
        return self.headline  
    class Meta:  
        ordering = ('headline',)

두 출판사를 만들려면 다음과 같이 하십시오.
p1 = Publication(title='The Python Journal')  
p1.save()  
p2 = Publication(title='Science News')  
p2.save()  
p3 = Publication(title='Science Weekly')  
p3.save()

문장을 한 편 더 만들고 다른 세 출판사와 연계하다
a2 = Article(headline='NASA uses Python')  
a2.save()  
a2.publications.add(p1, p2)  
a2.publications.add(p3)

좋은 웹페이지 즐겨찾기