Tuesday, June 28, 2011

Comparing ManyToManyFields

So I'm working on my first Django application, and I've run into a
stumbling block. In simplest terms, I've got two objects:

def Package(models.Model):

def Machine(models.Model):

I'm reading in information from some file, and need to compare against
objects already in the database. Ideally, I could just create these
objects in my code, compare to the existing Django objects, and add a
new entry if it's different from anything that exists already.

However, I've got that dang ManyToManyField in there, meaning I need
to first commit a Machine to the DB, and then add Packages to it.
Otherwise, of course I get:

ValueError: 'Machine' instance needs to have a primary key value before a many-to-many relationship can be used.

This seems non-ideal, since there's a pretty good chance I'll just
need to delete it from the database as a dupe of an existing Machine.

I see a couple of ways around this:

- Instantiate a Machine and a list of Packages, and compare them
separately. This isn't ideal, as my real objects likely have more
than 1 many-to-many relationship.

- Do database queries and whatnot directly. Yuck!

- Punt and just add/remove things from the database. This would
probably work fine now, but later on could definitely lead to scaling

Am I missing an obvious solution here? I've scoured the docs and
can't seem to come up with anything that doesn't make me feel icky.


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