开发者

Best Practice to link Multiple Files to model if number of Files can vary

I have an Accounting Module with a model like this:

class Accounting_period(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()
    base_pdf = models.FileField开发者_如何学运维()

I have a management function that runs every night at midnight and once filter(end_date__lt=datetime.datetime.today()) it generates an Invoice PDF via pisa and saves that file object at base_pdf. The PDF is available via a link on the site for the Accounting folks.

However after the end_date there are cases that crop up where additional work done needs to be back dated to that invoice. Then a new "Back dated" Invoice needs to be created like "Invoice-2.pdf" which only has the new back dated totals (so we don't confusing the Accounting folks). I want to save this to the Accounting_period model so that I can easily show links on the webpage. However I cringe at the thought of adding a bunch of FileFields to the model.

I am wondering if anyone has a nice solution to this problem. I am envisioning something with similarity to M2M where for each Accounting Period in the template I could do this:

templates.py
   <ul>
   {% for invoice in accounting_period_obj.invoices.all %}
      <li><a href="{{invoice.url}}">{{invoice.name}}</a>
   {% endfor %}
   </ul>

the ManyToManyField "through" argument looks promising but I am not linking to another Model.


You can use a ForeignKey (one-to-many relationship) for this:

class AccountingPeriodBackDated(models.Model):
    accounting_period= models.ForeignKey(AccountingPeriod, related_name="backdates")
    pdf = models.FileField()

Then use

templates.py
   <ul>
      <li><a href="{{accounting_period_obj.base_pdf.url}}">{{accounting_period_obj.base_pdf.name}}</a> (Original)</li>
      {% for o in accounting_period_obj.backdates.all %}
         <li><a href="{{o.pdf.url}}">{{o.pdf.name}}</a></li>
      {% endfor %}
   </ul>

For more info, see: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜