bspit
bspit

Reputation: 35

Django Form - Filter a list based on Foreign Key Value

So basically I have the following in my models.py

class Company (models.Model):
    title = models.CharField(max_length=100)
    short = models.CharField(max_length=50,default='NA') 

class AccountingGroups(models.Model):
    title = models.CharField(max_length=50, unique=True)
    description= models.CharField(max_length=150,blank=True)
    section = models.ForeignKey(Section, on_delete=models.PROTECT)

class Transaction (models.Model):
    description = models.CharField(max_length=100)
    date_created= models.DateField(auto_now_add=True)
    posting_date = models.DateField()
    user=models.ForeignKey(User, on_delete=models.PROTECT)
    company = models.ForeignKey(Company, on_delete=models.PROTECT)
    account_group = models.ForeignKey(AccountingGroups, on_delete=models.PROTECT)
    income_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0)
    expenditure_amt = models.DecimalField(max_digits=6, decimal_places=2,default=0)

Now I am displaying the transaction Form on the browser so to log in all the income and expenditure of a particular company. The below is the forms.py file.

class TransactionForm(ModelForm):
    #posting_date = DateField(input_formats=['%d/%m/%Y'])
    posting_date = DateField(widget=DatePickerInput(format='%d/%m/%Y').start_of('event active days'),
                               input_formats=('%d/%m/%Y',),
                               required=False)
    class Meta:
        model = Transaction
        fields = ['description','posting_date','account_group','income_amt','expenditure_amt']

Now the structure of the website is that each each company that i have in my database has a distinct url. When i go to each url i can view/edit or create a new/existing transaction for that particular company. Now what I'm asking if whether I can restrict the form so that it will show only the Accounting Groups for that particular company only rather than displaying all the accounting groups irrespective on which company I m trying to create the transaction on.

Upvotes: 0

Views: 47

Answers (1)

Matt Gleason
Matt Gleason

Reputation: 321

If you are looking to display a Company's AccountingGroups (and not transactions), you need a foreign key to filter off of. You currently don't have any in your AccountingGroups table, unless your Section FK links up to Company. Then you just query off that foreign key relationship.

AccountingGroups.objects.filter(section__company_id=pk)

No matter how you do it, you will need to pass in the company_id via your request.

Upvotes: 1

Related Questions