1

안녕 유래 사람들과 모범 사례, 장고 : ForeignKeys를 여러 모델

ForeignKeys를 선택할 하나 개의 모델을 참조하는 가장 좋은 방법은 무엇입니까

?

저는 GenericVehicle, Bikes 및 Cars 모델을 포함하는 대여 응용 프로그램을 작성 중입니다.

class GenericVehicle(models.Model): 
    licence = models.CharField(max_length=128) 
    ... 
    class Meta: 
     abstract = True 

class Bike(GenericVehicle): 
    engine_type = models.CharField(max_length=128) 
    ... 

class Car(GenericVehicle): 
    number_of_doors = models.SmallIntegerField() 
    ... 

이제 대여 된 차량을 등록하고자하는 모델이 있습니다. 나는 여기서 최고의 연습을 확신하지 못한다. 지금까지 나는 두 개의 외계인이 있었고 적어도 하나는 채워 졌는지 확인했습니다. 그러나이 솔루션은 매우 비효율적이며 여러 차량 유형에 맞게 확장되지 않습니다.

클래스 구조/정의를 개선하는 가장 좋은 방법은 무엇입니까?

class Rental(models.Model): 
    rental_bike = models.ForeignKey(Bike) 
    rental_car = models.ForeignKey(Car) 
    rental_date = ... 

감사합니다. 나는 이미 얼마 동안 효율적인 솔루션을 찾으려고 노력하고있다.

답변

3

장고는 GenericForeignKey을 제공합니다. GenericForeignKey는 참조 모델의 ContentType하고, 두 번째는 개체의 ID를 저장하는 저장 주셔서 모델, 하나의 필드로해야합니다

from django.db import models 
from django.contrib.contenttypes.models import ContentType 
from django.contrib.contenttypes import generic 

class Rental(models.Model): 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 

    rental_vehicle = generic.GenericForeignKey('content_type', 'object_id') 

을하지만 명심 데이터베이스 수준이 아닌 외래 키, 단지 장고 외부 키의 전형적인 동작 중 일부를 모방하는 것.