ManyToMany Relationship Django.How

Author avatar wrote on 08/06/2022

Model

class Sample(models.Model):
    users = models.ManyToManyField(User, blank=True) # if not blank=True it will not be required, null=True is meaningless

Add

sample_object.users.add(1,2)

 

Remove

sample_object.users.remove(1,2)

 

Remove all

sample_object.users.clear()

 

Retrieve

# retrieve (from the model where it was declared)
sample_object.users.all()
# retrieve (from the other model)
user_object.sample_set.all()

 

Get by order

sample_object.users.all()[0]
# in template
{{ sample_object.users.all.0 }}

 

Filter

Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()
# or
translators.filter(teams__id=company.id).count()
# or
Segment.objects.filter(tms=instance)   # the mtm field on segment model

 

Get value from multiple select

lang_list_str = request.POST.getlist('languages')
for language_str in lang_list_str:
    lang_obj = Language.objects.get(id=language_str)
    p1.target_languages.add(lang_obj)

 

Get value from multiple select

lang_list = request.POST.getlist('languages')
for language in lang_list:
    lang_obj = Language.objects.get(id=language)
    GlossaryLanguage(glossary=p1, language=lang_obj).save()

 

Retrieve in template

{% for locale in price.source_language_locales.all %}{{ locale }}
{% endfor %} # no set like OneToMany

# eg 2
{% for place in places %}
    Name: {{ place.name }}
    Area: 
{% for area in place.area.all %}{{ area }}
{% endfor %}
{% endfor %}

 

Remove Modal

Button – Make sure to change values on inclick

JS

View


        elif request.POST.get("form_type") == 'remove_source_locale':
            print('remove_source_locale')
            try:
                record_to_reomve_fk_from = TranslatorPrice.objects.get(id=request.POST['id'])
                record_to_reomve_fk_from.source_language_locales.remove(request.POST['fk_id'])
                messages.success(request, "Locale is removed successfully.")                
                print('Record Removed')
            except Exception as e:
                print("Exception remove M2M ==========================")
                messages.error(request, "Error. Something went wrong.")
                print(e)
                print("End of Exception  ==========================")
            return render(request, template_name, context)

 

Resources
CRUDgen Django CRUD generator