0

How to implement a list in a Django model?

Lets say I have a UserProfile model, and each user can have a list of mortgages (undefined quantity) defined by MortgageModel.

class MortgageModel(models.Model):
   bank_name = models.CharField(max_length=128)
   sum = models.BigIntegerField()

class UserProfile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   # list of morgtages?

my only idea is to make a old school list, where every mortgage can point to another one or null, like this:

class MortgageModel(models.Model):
   bank_name = models.CharField(max_length=128)
   sum = models.BigIntegerField()
   next_mortgage = MortgageModel(null=True, default=null)

class UserProfile(models.Model):
   user = models.OneToOneField(User, on_delete=models.CASCADE)
   mortgages = MortgageModel(null=True, default=null)

is there any other possibility?

4
  • Why not just use a ForeignKey relationship between UserProfile and MortgageModel? Commented Aug 31, 2016 at 21:16
  • list is simple to iterate and delete Commented Aug 31, 2016 at 21:38
  • In order to make a ForeignKey relation I would have to use filters to iterate over mortgages. Wouldn't it be faster to use a list? Commented Aug 31, 2016 at 22:14
  • A Django model is a Python representation of a database record. A model's fields (e.g. CharField) can only include data types that can be saved in database columns (e.g. character, integer, etc.) A Python list is not a data type that is represented in most common databases (ignoring the idea of a list serialised to XML/JSON/etc.) Commented Sep 1, 2016 at 2:00

1 Answer 1

3

You'll have to assign a ForeignKey to User , so that each Mortgate 'belongs' to a user. That is how a One-To-Many relationship is done. Then, if you want to get the list of Mortgages a user have, you'd filter them out like MortgageModel.objects.filter(related_user=user)

So, you'd have something like

Model

   class MortgageModel(models.Model):
       bank_name = models.CharField(max_length=128)
       sum = models.BigIntegerField()
       related_user = models.ForeignKey(UserProfile)

    class UserProfile(models.Model):
       user = models.OneToOneField(User, on_delete=models.CASCADE)

View

list_of_mortages = MortgageModel.objects.filter(related_user=user)
Sign up to request clarification or add additional context in comments.

5 Comments

how to iterate mortgages?
@user2449761 You can query them out using filters.
Thank you for comprehensive answer!
Wouldn't "oldschool" list be faster than filters?
@user2449761 oldschool list means wrong database modeling ;) Take a look at database normalization (good place to start en.wikipedia.org/wiki/Database_normalization)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.