Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Using models.DateField with auto_now_add = True wont show in page props #65

Open
buffmomoeveryday opened this issue Jan 18, 2025 · 4 comments

Comments

@buffmomoeveryday
Copy link

Hi I'm encountering this weird issue where the model's date field with auto_now_add field wont show up in page props, I'm guessing it's some thing to do with the InertiaJson Encoder as I'm new to this I dont know where to start to fix this.

Thank You

class DailyReport(models.Model):
    date = models.DateField(auto_now_add=True)
    issues_challenges = models.TextField(
        blank=True, null=True, help_text="Describe any challenges or blockers"
    )
    additional_notes = models.TextField(
        blank=True, null=True, help_text="Any relevant updates or comments"
    )

    def __str__(self):
        return f"Report by on {self.date}"

    @property
    def get_date(self):
        return self.date
<script setup>
import { Button } from '@/components/ui/button';
import { computed } from 'vue'
import { usePage } from '@inertiajs/vue3'

const page = usePage()

const daily_reports = computed(()=>page.props.daily_report)


</script>

<template>
{{ daily_reports }}

<div v-if="daily_reports">
<li v-for="report in daily_reports">
    <ul>
        Date : {{ report.id }}
    </ul>
</li>
</div>
<div v-else>
No Daily Reports
</div>
</template>

Image

@BrandonShar
Copy link
Collaborator

Under the hood the InertiaJsonEncoder uses Django's model_to_dict function and unfortunately this is an implementation detail of that function. model_to_dict doesn't include any fields that have editable=False and any fields with auto_now_add=True automatically set editable=False.

The best bet here is to convert this model to a dict or json before sending it to inertia.

If you have any ideas of how this could work more fluidly, let me know because I also think this is annoying behavior 😄

@scajanus
Copy link

scajanus commented Jan 25, 2025

Could we have a separate/single issue to collect the requirements for the serializer/JsonEncoder? This issue #18 is also related.

For me it would make sense to use something similar to Django REST Framework in specifying the fields, e.g.

class TeacherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Teacher
        fields = ('id', 'name', 'tenure')

Unfortunately Django doesn't directly allow extending the model's Meta class (see e.g. https://stackoverflow.com/a/1088649/4751065). One option would be to add a separate class similar to model's meta class to specify the field behavior:

class DailyReport(models.Model):
    date = models.DateField(auto_now_add=True)
    issues_challenges = models.TextField(
        blank=True, null=True, help_text="Describe any challenges or blockers"
    )
    additional_notes = models.TextField(
        blank=True, null=True, help_text="Any relevant updates or comments"
    )

    class InertiaMeta:
        fields = ('date', 'issue_challenges', )
        # OR exclude = ('additional_notes', )

Another option would be an optional serialize method in the model, that would be used if present, and use the default implementation otherwise. This allows the most flexibility if you need to customize behavior and not only what is present. Perhaps this should return a Python dictionary, still, that would be JSON-encoded later.

class DailyReport(models.Model):
    date = models.DateField(auto_now_add=True)
    issues_challenges = models.TextField(
        blank=True, null=True, help_text="Describe any challenges or blockers"
    )
    additional_notes = models.TextField(
        blank=True, null=True, help_text="Any relevant updates or comments"
    )

    def serialize(self):
        return {
            'uuid': generate_uuid(),
            'date': self.date,
            'issues_challenges': self.issues_challenges,
        }

But perhaps this discussion would better fit under a separate issue, since it is about design and not directly about solving the issue here. I'm only starting to learn Inertia.js, and at least for me it would be beneficial to first collect the expected behavior vs. current behavior (as well as behavior of the other adapters, where relevant) together, and then decide how to best meet those requirements.

@BrandonShar
Copy link
Collaborator

Thanks for your thoughts @scajanus , I really like both of your ideas! InertiaMeta in particular is very appealing because it matches an existing pattern in the ecosystem and would be very extensible if we wanted to expand it later.

Laravel and Rails don’t experience this same problem because they both have very clear, built in behavior for converting models to JSON, so customizing it is unique to Django.

I can open an issue and combine these later (im on my phone right now), but I’m leaning towards just implementing your InertiaMeta in a backwards compatible way and seeing if that solves most use cases.

@scajanus
Copy link

Sounds good! If it doesn't feel "risky" in the sense that it would somehow lock this down to a particular way of doing things and is easy to iterate on, I'd say let's go for it.

Also thank you for your comments on the way Laravel/Rails do things -- in a way, it is very weird that Django doesn't have anything like that, even though there are parts here and there that you can sort of cobble together to do something similar. Those seems to come with enough caveats that is probably a good idea to ultimately have your own JSON serializer, and that perhaps as a separate package.

The popularity of Django Rest Framework and on the other hand the easy of serializing small bits where needed probably explains the omissions, it's just if you want something generic (like here) there haven't been that many use cases, outside the niche that DRF already fills.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants