У меня есть такая модель:
class Grn(models.Model):
owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='grn_owner')
warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name="grn_warehouse")
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name="grn_vendor")
product1 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product1')
product1_quantity = models.IntegerField(default=0)
product2 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product2', blank=True, null=True)
product2_quantity = models.IntegerField(default=0, blank=True, null=True)
product3 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product3', blank=True, null=True)
product3_quantity = models.IntegerField(default=0, blank=True, null=True)
product4 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product4', blank=True, null=True)
product4_quantity = models.IntegerField(default=0, blank=True, null=True)
Как я могу l oop над объектом этой модели? Я пробовал что-то вроде этого:
class GRNFormView(CreateView):
model = Grn
template_name = 'GrnForm.html'
form_class = Grnform
def form_valid (self, form):
data = form.save(commit=False)
print("form.cleaned_data is ", form.cleaned_data)
data.owner = Employee.objects.filter(user = self.request.user.id)[0]
data.save()
print("data is", data)
for i in range(1,5):
if data.product(i):
print("product ", data.product(i))
else:
pass
Как я могу проверить, существует ли продукт в объекте и получить его значение?