无法使用资源uri发布一个相关对象:
http://127.0.0.1:8000/api/v1/job/
{ "name":"jobstestfinal2",
"payment":"/api/v1/payment/2/"
}
没有错误。只用null代替付款对象。
models.py
class Job(models.Model):
name = models.CharField(max_length=200)
class Payment(models.Model):
scheduled = models.DateTimeField()
job = models.OneToOneField(
Job,
related_name="payment",
blank=True,
null=True)
resource.py
class PaymentResource(ModelResource):
job = fields.ToOneField(
'myapp.resources.JobResource',
'job', null=True, blank=True)
class Meta:
queryset = Payment.objects.all()
resource_name = 'payment'
authorization = Authorization()
allowed_methods = ('get', 'put', 'post')
class JobResource(ModelResource):
payment = fields.ToOneField(
PaymentResource,
'payment',
related_name='job',
null=True, blank=True
)
class Meta:
queryset = Job.objects.all()
resource_name = 'job'
authorization = Authorization()
allowed_methods = ('get', 'put', 'post')
FYI以下终点工作正常:
GET工作,付款
POST作业[带付款对象]
付款[与工作uri]
付款[有工作对象]
答案 0 :(得分:0)
如果您想使用您发布的示例帖子网址。
http://127.0.0.1:8000/api/v1/job/
{ "name":"jobstestfinal2",
"payment":"/api/v1/payment/2/" # Not sure if you have to use payment_set or not.
}
将您的foreign key
从Payment
更改为Job
class Job(models.Model):
name = models.CharField(max_length=200)
payment = models.ForeignKey( # Changed from OneToOne to ForeingKey
Payment,
blank=True, # True means a job doesn't have to have a payment
null=True # Allowing the value NULL in your database
)
class Payment(models.Model):
scheduled = models.DateTimeField()
您可以向工作添加付款
job = Job(name='nice job')
job.save() # Your Job must have an ID before you can link it to a Payment
payment = Payment(scheduled='2014-1-1 10:00')
job.payment_set.add(payment)
job.save()
和付款的工作。
job = Job(name='nice job')
job.save() # Your Job must have an ID before you can link it to a Payment
payment = Payment(scheduled='2014-1-1 10:00')
payment.job = job # The difference is the _set.add when you do it through the Job model
payment.save()