如何保存关于manytomany Django的记录

时间:2017-09-08 19:20:17

标签: django django-models

下午好,我在Django 1.10中有我的应用程序,在那里我创建了Beneficiario和Auxilio模型之间的多对多关系,受益者领域是这种关系的关键,你可以看到,我需要一个额外的领域在由这种关系创建的模型中,所以使用'through'自定义模型Auxilio_Beneficiario,以便更好地理解:

models.py

class Dependencia(models.Model):
    dependencia = models.CharField(max_length=100)

class Beneficiario(models.Model):
    nombre = models.CharField(max_length=100)
    numeroDocumento = models.BigIntegerField()

class Auxilio(models.Model):
    auxilio = models.CharField(max_length=100)
    descripcion = models.TextField()
    dependencia = models.ForeignKey(Dependencia)
    beneficiario = models.ManyToManyField(Beneficiario, through='Auxilio_Beneficiario')

class Auxilio_Beneficiario(models.Model):
    auxilio = models.ForeignKey(Auxilio)
    beneficiario = models.ForeignKey(Beneficiario)
    fechaEntrega = models.DateField(null=True)

我遇到的问题是我不知道如何在模型Auxilio_Beneficiario中记录信息:

views.py

def asignaAuxilio(request):
    if request.method == 'POST':
        beneficiario = Beneficiario.objects.get(numeroDocumento=request.POST['documento'])
        #
        #
        #No se como grabar los campos auxilio,beneficiario,fecha de entrega
        #
        # 
        return render(request, 'asignaAuxilio.html')

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果您想知道如何访问through模型,那么最简单的方法是将related_name添加到ForeignKey中,如下所示:

class Auxilio_Beneficiario(models.Model):
    auxilio = models.ForeignKey(Auxilio, related_name='auxilio_beneficiario')
    beneficiario = models.ForeignKey(Beneficiario, related_name='auxilio_beneficiario')
    fechaEntrega = models.DateField(null=True)

现在您可以像这样访问它:

if request.method == 'POST':
    beneficiario = Beneficiario.objects.get(numeroDocumento=request.POST['documento'])

    through_model = beneficiario.auxilio_beneficiario.first() # Or filter based on your system's needs
    through_model.fechaEntrega = request.POST.get('something')
    through_model.save()


    return render(request, 'asignaAuxilio.html')

我是否回答了你的问题?