Last active
October 20, 2016 09:20
-
-
Save herrersystem/fabed584aa67dec1c9fe5e023e087c8c to your computer and use it in GitHub Desktop.
[Django] Utiliser l'héritage dans nos modèles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from my_app.models import * | |
my_books = Book.objects.all() #Search in Book only. | |
my_collection = Collection.objects.all() #Search in all collection. | |
for elem in my_collection: | |
if elem.categorie == 'book': | |
print(elem.book.author, elem.book.title) | |
else: | |
print(elem.music.artist, elem.music.album) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
CATEGORIES = [ | |
('book', 'book'), | |
('music', 'music') | |
] | |
class Collection(models.Model): | |
global CATEGORIES | |
name = models.CharField(max_length=64) | |
description = models.CharField(max_length=256) | |
categorie = models.CharField(max_length=5, choices=CATEGORIES) | |
def __str__(self): | |
return self.title | |
class Music(Collection): | |
title = models.CharField(max_length=64) | |
artist = models.CharField(max_length=32) | |
album = models.CharField(max_length=32) | |
def __str__(self): | |
return self.title | |
class Book(Collection): | |
title = models.CharField(max_length=64) | |
author = models.CharField(max_length=32) | |
def __str__(self): | |
return self.title |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment