Wednesday, September 28, 2011

Create singular instance with ManyToManyField input as ids

Hi guys,

I need to create Django model instances from raw data, which comes
from a dict. Example model:


class Worker(models.Model):
name = models.CharField()

class Project(models.Model):
name = models.CharField()
subject = models.CharField()
workers = models.ManyToManyField('Worker')


Data arrives at the Server as raw data, e.g.


worker_1 = {"pk": 1, "name": "Joe"}
worker_2 = {"pk": 2, "name": "Julia"}
worker_3 = {"pk": 3, "name": "Jacob"}

proj_1 = {"pk": 4, "name": "My first Django", "subject": "Manage
Staff", "workers": [1, 2]}
proj_2 = {"pk": 5, "name": "Something else", "subject": "About
cooking", "workers": [1, 3]}


Data can arrive in "non logical" order from the client. E.g.


proj_1 = {"pk": 4, "name": "My first Django", "subject": "Manage
Staff", "workers": [1, 2]}
worker_2 = {"pk": 2, "name": "Julia"}
...


My idea was to use sweet syntax like this to create the models:


worker_1_inst = Worker(**worker_1)
proj_1_inst = Project(**proj_1)


But Django needs proper instances as foreign fields. For a simple
foreign key I guess I could access the id-fields with appending "_id"
to write the reference as id. But what can I do in the case of m2n? To
resolve the the references in the raw data prior creating Django
instances seems to become totally messy.

Damn, I'm really stuck (and embarrased about the error in reasoning.)

Thanks a lot in advance.

Jan

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment