A
A
Alex Xmel2020-04-16 03:18:38
Django
Alex Xmel, 2020-04-16 03:18:38

How to bind models in Django given conditions?

There are 2 models:

class Code(models.Model):
    name = models.CharField(max_length=40, unique=True, verbose_name='Наименование')
    used = models.BooleanField(default=False, verbose_name='Используется ')

class Ordering(models.Model):
    num = models.PositiveIntegerField(auto_created=True, verbose_name='Номер заявки')
    system = models.ForeignKey(Code, on_delete=models.DO_NOTHING)


it is necessary that in the admin panel, about adding an entry to Ordering, not all fields from the Code model are displayed in the system field, but only those fields used where the value is True. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WStanley, 2020-04-16
@WStanley

Hey!
Something like this should work
link to the source
in admin.py

@admin.register(Ordering)
class OrderingAdmin(admin.ModelAdmin):

  def formfield_for_foreignkey(self, db_field, request, **kwargs):
          if db_field.name == "system":
              kwargs["queryset"] = Code.objects.filter(used=True)
          return super().formfield_for_foreignkey(db_field, request, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question