twingo
twingo

Reputation: 119

List only unassigned values for many to many field in Django

I have two models as follows:

class Fruit(models.Model):
    name = models.CharField(max_length=20)

class Season(models.Model):
    name = models.CharField(max_length=20)
    fruits = models.ManyToManyField(Fruit, related_name='seasonal_fruit')

I want to add the fruits to the Season if only they are not assigned to any other Season object.

Also, I want to display the list of these distinct (i.e. not assigned to any other Season object) in the SeasonAdmin.

How can I achieve this?

Upvotes: 0

Views: 70

Answers (1)

Priyanshu Panwar
Priyanshu Panwar

Reputation: 1

class SeasonAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "fruit":
            f = [x for x in Fruit.objects.all()]
            s = [y for y in Season.objects.all()]
            for a in y:
                for b in y.fruit.all():
                    f.remove(b)
            kwargs["queryset"] = f
        return super().formfield_for_manytomany(db_field, request, **kwargs)

Upvotes: 1

Related Questions