【发布时间】:2014-03-24 04:40:24
【问题描述】:
我对这个问题进行了很多搜索,并在 Stack Overflow 上解决了一堆相关问题,但似乎没有关于如何“通过”中间模型实现多对多关系的明确答案(或者我可能错过了)。
我有一个名为 Sample 的模型,它与 Region 具有多对多的关系。有一个连接两者的中间模型,名为 SampleRegion。我目前没有保存任何关于中间模型的额外信息,但我可能会在未来保存。
这是我的模型:
class Sample(models.Model):
sample_id = models.BigIntegerField(primary_key=True)
description = models.TextField(blank=True)
objects = models.GeoManager()
regions = ManyToManyField(Region, through='SampleRegion')
class Meta:
db_table = u'samples'
def save(self, **kwargs):
# Assign a sample ID only for create requests
if self.sample_id is None:
try: id = Sample.objects.latest('sample_id').sample_id + 1
except Sample.DoesNotExist: id = 1
self.sample_id = id
super(Sample, self).save
class Region(models.Model):
name = models.CharField(max_length=100, unique=True)
def __unicode__(self):
return self.name
class Meta:
db_table = u'regions'
class SampleRegion(models.Model):
sample = models.ForeignKey('Sample')
region = models.ForeignKey(Region)
class Meta:
unique_together = (('sample', 'region'),)
db_table = u'sample_regions'
这是我用来编写资源的一种方法。这是不正确的,我无法找出正确的方法:
class SampleResource(ModelResource):
regions = fields.ToManyField("tastyapi.resources.RegionResource",
"regions")
class Meta:
queryset = models.Sample.objects.all()
allowed_methods = ['get', 'post', 'put', 'delete']
authentication = ApiKeyAuthentication()
authorization = ObjectAuthorization('tastyapi', 'sample')
excludes = ['user', 'collector']
filtering = {
'version': ALL,
'sesar_number': ALL
}
validation = VersionValidation(queryset, 'sample_id')
def hydrate_regions(self, bundle):
# code to create a new SampleRegion object by getting a list of
# regions from bundle.data['regions']
class RegionResource(ModelResource):
class Meta:
queryset = models.Region.objects.all()
allowed_methods = ['get']
resource_name = "region"
filtering = {
'region': ALL,
}
这就是我发出 POST 请求的方式:
post_data = {
'regions': ["/tastyapi/v1/region/2/"],
'description': 'Created by a test case',
}
client.post('/tastyapi/v1/sample/', data = post_data,
authentication = credentials, format = 'json')
此请求无效,因为此时 bundle.data['regions'] 为 None
它到达hydrate_regions。
有人对我应该如何实施此方案有任何建议吗?
【问题讨论】: