Skip to content

Instantly share code, notes, and snippets.

@herrersystem
Last active October 20, 2016 09:20
Show Gist options
  • Save herrersystem/fabed584aa67dec1c9fe5e023e087c8c to your computer and use it in GitHub Desktop.
Save herrersystem/fabed584aa67dec1c9fe5e023e087c8c to your computer and use it in GitHub Desktop.
[Django] Utiliser l'héritage dans nos modèles
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)
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