我在尝试将数据添加到django模型中的many2many字段时遇到意外错误。我不确定为什么我没有收到相关数据(payment_method)
对于以下型号
class PaymentMethod(models.Model):
MONTHLY_DIRECT_DEBIT = 'MDD'
CASH_OR_CHEQUE = 'CAC'
QUARTERLY_DIRECT_DEBIT = 'QDD'
PAYMENT_CHOICES = (
(MONTHLY_DIRECT_DEBIT, 'Monthly Direct Debit'),
(CASH_OR_CHEQUE, 'Cash or Cheque'),
(QUARTERLY_DIRECT_DEBIT, 'Quarterly Direct Debit'),
)
unique_id = models.CharField(max_length=3, choices=PAYMENT_CHOICES)
name = models.CharField(max_length=255, unique=True)
class Tariff(models.Model):
name = models.CharField(max_length=255)
supplier = models.ForeignKey(Supplier)
payment_method = models.ManyToManyField(PaymentMethod)
region = models.ManyToManyField(Region)
class Meta:
unique_together = ('name', 'supplier')
class Supplier(models.Model):
unique_id = models.IntegerField(unique=True)
name = models.CharField(max_length=255, unique=True)
我正在尝试通过以下方式将付款方式数据添加到关税中:
supplier = Supplier.objects.get(unique_id=region.default_supplier.unique_id)
payment_method_instance = PaymentMethod.objects.get(unique_id=payment_method['id'])
tariff, created = Tariff.objects.get_or_create(name=tariff, supplier=supplier)
if created:
sys.stdout.write('Tariff {} not found for Supplier: {}\n'.format(tariff, supplier))
tariff.payment_method.add(payment_method_instance)
当我尝试通过以下方式访问关税的付款方式时,我收到以下错误:
>>> tariff1.payment_method
Out[4]: <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager at 0x11326c710>
>>> tariff.payment_method.unique_id
Traceback (most recent call last):
File "", line 3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-a0370f309c95>", line 1, in <module>
tariff.payment_method.unique_id
AttributeError: 'ManyRelatedManager' object has no attribute 'unique_id'
答案 0 :(得分:4)
payment_method
模型中的Tariff
字段是一个M2M字段,因此它不会返回一个对象,它将返回一组对象。因此,您无法访问.unique_id
attr,因为它不是PaymentMethod
对象。您可以获取与当前unique_id
对象相关的所有PaymentMethod
个对象的Tariff
值:
>>> tariff1.payment_method.all().values_list('unique_id', flat=True)