2012-09-29 75 views
1

我怎麼能汽車(Car)添加到車庫(Garage)如果我有一箇中間模式?我不明白這。將數據添加到數據庫(中間模型)

class Car(models.Model): 
    name = models.CharField(max_length=50) 
    price = models.DecimalField()  

class GarageCar(models.Model): 
    car = models.ForeignKey('Car') 
    quantity = models.IntegerField() 

class Garage(models.Model): 
    name = models.CharField("Garage_Name", max_length=30) 
    cars = models.ManyToManyField('GarageCar', blank=True, null=True) 
    owner = models.ForeignKey(User, related_name='owner_garage', verbose_name='Owner Garage') 

意見

def add_car(request, car_id): 

如果我有兩個車型(轎車和車庫與外地車= models.ManyToManyField( '汽車')創建這樣的事情:

def add_car(request, car_id): 
    if request.user.is_authenticated(): 
     user = request.user 
     car = Car.objects.get(id = car_id) 
     e = car.garage_set.create(name='example_name', owner=user) 

    return render_to_response('add.html') 

回答

1

首先,您需要對模型進行一些更改:

  1. 中間模型GarageCar需要有一個外鍵CarGarage
  2. 當您定義多對多字段時,請使用through參數指定中間表。

如下更改型號:

class GarageCar(models.Model): 
    car = models.ForeignKey('Car') 
    garage = models.ForeignKey('garage') 
    quantity = models.IntegerField() 

class Garage(models.Model): 
    name = models.CharField("Garage_Name", max_length=30) 
    cars = models.ManyToManyField('Car', through='GarageCar') 

然後,您可以將車添加到車庫以下:

GarageCar.objects.create(car=car, 
         garage=garage, 
         quantity=1, 
         ) 

參見extra fields on many-to-many relationships的文檔獲取更多信息。