vandelay
vandelay

Reputation: 2065

Filtering between related objects in admin panel

Is there a way to pick the shown objects in the admin panel?

for example I have two users, egg and aegon. If I'm looking at the user egg's profile under User transactions I can see all transactions, those for aegon aswell. But I'd like to filter this to only show egg's transactions.

enter image description here

models:

class transaction(models.Model):
    amount = models.IntegerField()
    holding = models.ForeignKey(holding, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)

    def __str__(self):
        return "amount: " + str(self.amount) + " - ip : " + str(self.holding.name) + " - user: " + str(self.user.username)

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    ip = models.IntegerField(default=0)
    ingameName = models.CharField(max_length=50, default='NotSet')      
    userprofit = models.IntegerField(default=0)

    user_transactions = models.ForeignKey(transaction, on_delete=models.CASCADE, blank=True, null=True)

admin:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'

class UserAdmin(UserAdmin):
    inlines = (UserProfileInline, )

Upvotes: 0

Views: 40

Answers (1)

wanaryytel
wanaryytel

Reputation: 3482

Yep, but you'll have to override the admin form for that and filter the choices in the __init__() method of the form. The form __init__() should look sth like this (warning - untested code):

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['user_transactions'].choices = transaction.objects.filter(user_id=user_id)

For information about how to override admin form, check out the docs: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form

Upvotes: 1

Related Questions