2017-09-11 1 views
0

Dites-moi comment décrire cette connexion: enter image description hereDécrire la relation polymorphes de Django

Il y a une table où il peut y avoir différents types de documents (Type1, Type2 ou Type3).

models.py

from django.db import models 
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation 
from django.contrib.contenttypes.models import ContentType 

class General(models.Model): 
    field1 = models.CharField(max_length=512, blank=True, null=True) 
    field2 = models.CharField(max_length=512, blank=True, null=True) 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    content_object = GenericForeignKey('content_type', 'object_id') 

    class Meta: 
     db_table = 'General' 

    class Type1(models.Model): 
    name = GenericRelation(Product) 
    address = models.CharField(max_length=512, blank=True, null=True) 
    number = models.CharField(max_length=256, blank=True, null=True) 

    class Meta: 
     db_table = 'Type1' 

Comment établir une connexion et choisissez ce que je veux taper un type, par exemple Type2?

Répondre

0

Cela semble correct, sauf la ligne:

name = GenericRelation(Product) 

devrait être:

name = GenericRelation(General) 

afin de former la relation générique inverse correcte.