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):

如果我有两个模型(Car 和 Garage with field cars = models.ManyToManyField('Car') 我会创建这样的东西:

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')
4

1 回答 1

1

首先,您需要对模型进行一些更改:

  1. 中间模型GarageCar需要具有Car和的外键Garage
  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,
                         )

有关更多信息,请参阅有关多对多关系的额外字段的文档。

于 2012-09-29T23:06:52.873 回答