Django removing object from ManyToMany relationship - django

How would I delete an object from a Many-to-Many relationship without removing the actual object?
Example:
I have the models Moods and Interest.
Mood has a many-to-many field interests (which is a models.ManyToManyField(Interest)).
I create an instance of Moods called my_mood. In my_moods's interests field I have my_interest, meaning
>>> my_mood.interests.all()
[my_interest, ...]
How do I remove my_interest from my_mood without deleting either model instance? In other words, how do I remove the relationship without affecting the related models?

my_mood.interests.remove(my_interest)
Django's Relations Docs
Note: you might have to get an instance of my_mood and my_interest using Django's QuerySet API before you can execute this code.

If you need to remove all M2M references without touching the underlying objects, it's easier to work from the other direction:
interest.mood_set.clear()
While this does not directly address the OP's question, it's often useful in this situation.

In your case you can simply clear the relationship
my_mood.interests.clear()
Then perhaps when you are again creating new relation in your serializer you can do something like this
interests = Interests.objects.get_or_create(name='Something')
my_mood_obj.tags.add(tag[0])
my_mood_obj.save()

model.field.remove(object_you_want_to_remove)
In this case use: my_mood.interests.remove(my_interest)

Related

Django admin showing object ID instead of __str__ when deleting

I'm not sure if this is a bug, by design or something I've done.
I'm seeing the same issue as this issue when deleting an item with a M2M relationship where the object ID is returned instead of str.
The str is set correctly and displays correctly otherwise, just not when deleting an item. The object ID shows up instead.
I've tested by creating a new Django project and a simple model with 2 classes related by M2M but get the same thing.
The only way I've found, which isn't ideal, is to use the "through" option on the field.
One I have many relationships like this in various models.
Two, returning str on the intermediate model I have to display both fields so that it makes sense when deleting from either of the related models.
Anyone have any thoughts? Is using "through" the only option?

Third-party-app for merging Django user objects?

I need to merge two users in a Django database.
So I wonder if there is any simple way (maybe a dedicated app) to do that?
For example:
We have user_a and user_b and some models that have foreign keys to the User model (Books, Interests, Teams and so on…).
By merging users, I want to delete the object user_b and to set all foreign keys pointing to this object to point to user_a. And – this is my main concern – I want the objects that need to be changed because they reference the to-be-deleted object to be determined automatically without having to specify a list of those Models and foreign key fields in them manually.
Is this already implemented and I'm reinventing the wheel?
Is this possible?
If not, please show me the way to do it: how can I build a list of Django models that have a foreign key to a specific model (User in my case) in runtime?
Thank you for your time.
I found this snippet http://djangosnippets.org/snippets/2283/ . I'm going to have to modify it though, to make it recursive. I will share my code once I'm done.
With Django 1.8 and beyond, you could achieve this robustly using the Model _meta API.
Specifically, you could use Options.get_fields. This will even let you handle generic relations.
You'll need to consider for each related field whether you want to add or replace on merge. This decision depends on your application logic and corresponding schema choices.
u = User.objects.get(pk=123)
related_fields = [
f for f in u._meta.get_fields()
if (f.one_to_many or f.one_to_one)
and not f.concrete
]
for f in related_fields:
# use field's attributes to perform an update

Enforce at least one value in a many-to-many relation, in Django?

I have have a many-to-many relation in a Django(1.4) model.
class UserProfile(models.Model):
foos = models.ManyToManyField(Foo)
I want to enforce that each User(Profile) has at least one Foo. Foos can have zero-or-more User(Profiles)s.
I would love this to be enforced at the model and admin levels, but just enforcing it in the admin would be sufficient.
If I understand correctly, 'many' in Django-speak is zero-or-more.
I want a ManyToOneOrMore relation. How can I do this?
Thanks,
Chris.
You can't enforce this on at the model level as #Greg details, but you can enforce it on a form by simply making the field required. This won't prevent anyone with shell-level access from manually creating a UserProfile without a foo, but it will force anyone using a browser-based form method of creation.
Unfortunately, I don't think this is possible at the model level because ManyToMany data is saved separately from other model fields. You should be able to enforce it at the admin level by specifying a custom form, and writing a clean() method on the form.

Filter through a related model django

How can I generate a query_set through a related model?
For example, how can I do this:
UserProfile.objects.filter(user.is_active=True) # Can't use user.is_active to filter
Trivial question, trivial answer. But I'll keep it here for posterity's sake.
UserProfile.objects.filter(user__is_active=True)
This is well documented in the Django docs.
From the Django documention
Django offers a powerful and intuitive way to "follow" relationships in lookups, taking care of the SQL JOINs for you automatically, behind the scenes. To span a relationship, just use the field name of related fields across models, separated by double underscores, until you get to the field you want.
In your example this would be:
UserProfile.objects.filter(user__is_active=True)
The easiest way to follow a relationship is to use a simple "__".
UserProfile.objects.filter(user__is_active=True)
These can be changed together as well (ie user_parent_email='abc#def.com')

Different models sharing one ID list

In my application I've added a "Facebook Comment Box" (on different pages, for different objects). Each object has its own comments list so I need to provide a unique (across the site) ID for every single one of them.
What would be the best approach for achieving this: An abstract model, from which all other models will inherit? A dummy model with a ForeignKey relation? What are your ideas?
You may want to implement GUIDs:
http://www.codecommit.com/blog/database/are-guids-really-the-way-to-go
Here's a django module that gives you a field for 'em:
http://pypi.python.org/pypi/softwarefabrica.django.utils/
... you can safely use them in URLs -- won't be pretty, but for comments and other things without obvious URL-able titles, GUIDs work out well.
Solved with a dummy model :
http://fromzerotocodehero.blogspot.com/2010/11/providing-uniqueness-of-different.html