Query ManytoMany field

Hi everyone,
I am trying to build a form with filtered many-to-many field.
so i created Objects:

Dayname

  1. name=sunday
  2. name=monday

Submain

  1. name:Math
    days(ManytoMany field): Sunday Monday
  2. name: Sport
    days(ManytoMany field): Tuesday
  3. name:Dance
    days(ManytoMany field): Sunday Tuesday

Day
1)name(Char field)=“Sunday”
hog1(ManytoMany field, filterd): will show me only Dance and Math to pick.

how can i filted this hog1 manytomany field in the form.py ?
should i change the Name of Day model into forginkey of dayname?
thank you for any help.

I Have 3 Models:

Models.py

class Dayname(models.Model):
 name = models.CharField(verbose_name="day", max_length=200, null=True)
 def __str__(self):
    return self.name


class Submain(models.Model):

  name = models.CharField(verbose_name="שם החוג", max_length=200, null=True)
 days = models.ManyToManyField(Dayname, verbose_name="ימי פעילות", 
 related_name="active", max_length=200, null=True,
                              )

def __str__(self):
    return self.name




class Day(models.Model):
  name = models.CharField(verbose_name="יום", max_length=200, null=True)
  hog2 = models.ManyToManyField(Submain, verbose_name="חוג 2 ביום", 
     related_name="hog2", max_length=200, null=True,
                              )

  def __str__(self):
    return self.name

forms.py

class DaysForm(ModelForm):

def __init__(self, *args, **kwargs):
    super(DaysForm, self).__init__(*args, **kwargs)
    self.fields['hog1'].required = False
    self.fields["hog1"].widget = CheckboxSelectMultiple()
    self.field['hog1'].queryset = Submain.objects.filter(days__in__name="sunday")

When requesting help here with specific code, there are three tips to keep in mind to allow others here to try and provide constructive and useful assistance.

  1. When posting code, post it between lines consisting of three ` (backtick) characters. That allows the formatter to make your code look good.
    example (the line after this consists only of ```:
class DayForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

The line before this consists only of ```

  1. Include all of the relevant code - in this case, it’s going to be helpful to see the models (not just a general description) and possibly the view (see item 3) as well as the form.

  2. Include the specific error message that you’re getting, including the traceback and any other information presented to you at the time of the error.

Ken

Ok, sorry. Will change that asap. I am not near the pc.
Did you understand what i needed, can i get any help please?

I think I’m getting a general idea of what you’re trying to get at, but I don’t have enough information at this time to provide any useful assistance. Maybe someone else is willing to make some guesses.

i have update the post, can you check now if it helps ?

I’m not clear here - are you saying that you want to have the filters apply while the form is already rendered? (In other words, making the change on the fly) Or are they entering the day on one form and then going to another page (or refreshing that page) with the filtered selection?

The two answers are different. If you’re looking to change the select box on the form in the browser, that’s not something that Django can do - that’s going to require some javascript code to do that.
On the other hand, if you’re looking to have them enter the day on one form, and use that day to filter the select box on another page, then that can be done within Django.

if you’re looking to have them enter the day on one form, and use that day to filter the select box on another page, then that can be done within Django.

yes that one,
just wanted to filter the items inside a manytomany field before the page render.

Found Solution:

self.fields['hog1'].queryset = Submain.objects.filter(days__in=['id of dayname'])

And we may probably want to add .distinct().

1 Like

there is a way of getting the vaule in forms.py:
like this :slight_smile:
name=self.fields["name"].text