I have:
class MyUser(Model):
today_ref_viewed_ips = ManyToManyField(
UniqAddress,
related_name='today_viewed_users',
verbose_name="Adresses visited referal link today")
...
On some croned daily request I do:
for u in MyUser.objects.all():
u.today_ref_viewed_ips.clear()
Can it be done on DB server with update?
MyUser.objects.all().update(...)
Ok, I can't update, thanks. But only thing I need is to TRUNCATE m2m internal table, is it possible to perform from django? How to know it's name whithout mysql's console "SHOW TABLES"?
Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.
You need to use . set() or . add() for updating a M2M field.
Updating A Post With Tags This is the primary purpose of this article—updating the many to many relationship between the post and tags. To update the post along with the tags, we need to add another view function called update_post .
If you want to update the m2m fields only and do not want to delete the m2m objects you can use the following:
#if you have **list of pk** for new m2m objects
today_ref_pk = [1,2,3]
u = MyUser.objects.get(pk=1)
u.today_ref_viewed_ips.clear()
u.today_ref_viewed_ips.add(*today_ref_pk)
for django >=1.11 documentation:
# if you have the **list of objects** for new m2m and you dont have the
# issue of race condition, you can do the following:
today_ref_objs = [obj1, obj2, obj3]
u = MyUser.objects.get(pk=1)
u.today_ref_viewed_ips.set(today_ref_objs, clear=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With