Home > Enterprise >  How to define models in django that provides custom values based on pre-selection for a field?
How to define models in django that provides custom values based on pre-selection for a field?

Time:07-22

Given the following model that stores the user's wish list for reading books:

class ReadingList(models.Model):
    user_id = models.ForeignKey(UserInfo, on_delete=models.DO_NOTHING, null=False, blank=False, default=None, db_column='user_id')
    book= models.CharField(max_length=255, blank=False)
    creation_time = models.DateTimeField(blank=True)

    class Meta:
        unique_together = (('user_id', book),)

I want to create a model that helps in tracking the time spent in the reading the book on different days which looks something like this:

class ReadingTracker(models.Model):
    user_id = models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='user', blank=False, db_column='user_id')
    book= models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='book-to-read', blank=False, db_column='book')
    time = models.DateTimeField(blank=True)
    time_spent = models.floatfield()

On the client-side (corresponding to ReadingTracker) for both the fields user_id and book I see that ReadingList object (1), ReadingList object (2), ... are listed. But, this is not working as expected. What I want to achieve are the following:

  1. For user_id field I want to see the something like dummy_uid1, dummy_uid2, ... to be listed.

  2. Consider dummy_uid1 wants to read book1 and book2 whereas dummy_uid2 wants to read book1 and book3. When dummy_uid1 is selected as user_id, I want only book1 and book2 to be listed for selection.

How do I define the model in django rest framework to achieve this? Any suggestions related to the above would be much appreciated and thank you in advance.

CodePudding user response:

There are two parts to this question:

  1. If you want to see a different value than ReadingList object (1) then you need to define the __str__ value of your model, you can do this like so:

    class ReadingList(models.Model):
       ...
    
       def __str__(self):
          return f'{self.user_id}' # return whatever string you want to display
    
  2. If you want to just display the books for a particular user then you can use a filter() (see the Django documentation):

    reading_list = ReadingList.objects.get(...)
    ReadingTracker.objects.filter(user_id=reading_list)
    

However, I would add that you have a user_id on your ReadingList object which does seem to connect to a User model, but your user_id on ReadingTracker is a ForeignKey relation to ReadingList, which is confusing. I would suggest renaming the field or actually making it link to the User model (though this is unnecessary as you can still filter by User through the ReadingList model).

  • Related