I searched this issue many times and went through a bunch of related stack overflow questions, but there seems to be no definitive answer on how to implement many-to-many relationships through an intermediate model (or maybe I skipped this).
I have a model called Sample that has many-to-many relationships with Region. There is an intermediate model that connects two called SampleRegion. I do not currently save additional information about the intermediate model, but I could in the future.
Here are my models:
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):
And here is one approach I took to write resources. This is not correct, and I cannot figure out how to do this correctly:
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):
This is how I make a POST request:
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')
This query does not work because bundle.data ['regions'] is None
by the time it reaches hydrate_regions
.
Does anyone have any recommendations as to how I should execute this script?