I have a fairly simple model in Django, let's say Book:
class Book(models.Model):
name = models.CharField(max_length=255, default="")
description = models.TextField(null=True, blank=True)
creation_date = models.DateTimeField()
Because the structure and data basically comes from an external API, I have contained it in its own app and I rather not want to modify it.
Now I want to add another source of different books to the project and I'm not really sure what the best solution is here.
Let's say the second model is:
class NextBook(models.Model):
title = models.CharField(max_length=255, default="")
long_description = models.TextField(null=True, blank=True)
created = models.DateTimeField()
So the basic fields are there, but have different names. To get the two together, I can probably use another model with a GenericForeignKey:
class BaseBook(models.Model):
book_type = models.ForeignKey(ContentType)
book_id = models.PositiveIntegerField()
book_object = generic.GenericForeignKey('book_type', 'book_id')
But then I cannot query for all the book as e.g. BaseBook.objects.all().order_by('created') wouldn't work. Surely, I could go on and duplicate a datetime field in the base model and then the title and so on, but I think that would be the wrong direction. Also inheritance seems not a choice if I don't want to touch the specific models.
I am looking for some design pattern or something that let's me efficiently 'plug in' more providers and query for all objects, while not making a huge mess of model structure and database queries.
There’s a fundamental contradiction in your question. Do you assume that, for a given book, the created reported by different providers will be the same?
If yes, why can’t you make a created field on your BaseBook and order by that? You can then drop the creation_date from your Book (or just ignore it, if you don’t want to touch it).
If not, how do you want to order books (not provider entries) by created in the first place?
Also, what you’re trying to do sounds like a good case for a free-schema database like MongoDB. There, you can embed provider entries directly in your book documents, then order by something like “created from the first provider entry for the book”. Thus, you maintain self-contained provider documents without denormalization. You still need created to mean the same thing for all providers, though.
Related
I am trying to make an OfferUp-like web app using Django Framework. Everything has been going great until I ran into a problem. How could I make it so that users can upload multiple pictures, instead of just one using the models.ImageField() function? You know? We might have users that only have 5 pictures to upload, while another user might have 8. How could I make it so that users can upload into the database as many pictures as they want?
What I'm going to suggest isn't that much different from the comment above (i don't have enough reputation to make a comment), so I'm just going to add a code snippet:
class Item(models.Model):
name = models.TextField()
class ItemImage(models.Model):
name = models.TextField()
item = models.ForeignKey(Item, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/')
and say: If you have more than one model with many images, rather than repeating the code you can just make a model (class) that will be inherited as the foreign key.
I've been reading through the Django documentation and looking over some of the other answers on the site for a couple of hours now, yet I still can't get it to sink in. I know this isn't Django specific, but the examples I use will be from a Django project.
My question boils down to when is it appropriate to use each:
Many-to-many relationships
Many-to-one relationships
One-to-one relationships
One-to-one, more or less makes sense to me.
Now for the other two. While I understand the differences between them in isolation, when it comes to using them practically in a project, I get confused. Here is an example:
class User(AbstractUser):
pass
class Listing(models.Model):
title = models.CharField(max_length=64)
description = models.TextField()
class Watchlist(models.Model):
user = models.ForeignKey(User, related_name='watchlist', on_delete=models.CASCADE)
item = models.ManyToManyField(Listing)
class Comment(models.Model):
user = models.ForeignKey(User, related_name='comments', on_delete=models.SET_NULL)
comment = models.TextField()
Would this be the correct use of Many-to-one(ForeignKey) and Many-to-many?
Should Watchlist.item be a ForeignKey? Or is M2M correct?
Wouldn't it simplify to make the 'Watchlist' part of the User class? (give them an empty list to populate with listing ID's)
Why is Watchlist.user not a One-to-one relationship, if each watchlist belongs to a single user, and a user can only have one list?
Apologies for my stupidity, I just can't get this to sink in!
Thank you.
edit: Context, the models are from a 'learning' project I was working on intended to be an auction site, similar to eBay. The watchlist is sort of a 'wish' list... for the user to watch an item, not for site to watch a user!
To explain it simply these django-models or objects represents tables in your database and the fields are like the columns in them. So with a one-to-one relation you can only have one row in one table relating to one row in another table. For example one user in the user table (represented by one row) can only relate to one row in a profile table. But your user can have many comments, so this would be a one-to-many/foreignkey relation (if you set unique=true on a fk, it will in practice function as 1:1). If the users can collaborate on writing comments, or for example as here on stackoverflow where users can edit other users comments, that would be a many-to-many relation.
Database design can be complicated/complex, especially using an ORM without basic knowledge of SQL and how it all works beneath. In general it requires a bit of planning even for a simple application.
my problem is the following. I have two models in the database, which I link together using a ManyToMany relationship. For the admin page I currently use "admin.TabularInline" to bind different objects to one via the graphic. I still want to specify an order in the connections, preferably numbers which represent an order for processing. A bit more figuratively described I have the model "Survey" and the model "SurveyQuestion". So I connect many SurveyQuestions with the Survey. But I can't specify an order, because I don't have an additional field for it. It is not known before how many questions will be in a survey. Nor is it known which questions will be inserted. Usually they are built during the compilation of the survey and may be used later for another survey. I am grateful for every tip!
This can be achieved by defining a custom relationship table between the Survey and SurveyQuestion using through argument. For example you can define a relationship model:
class Question(models.Model):
question = models.CharField(max_length=256)
class Survey(models.Model):
name = models.CharField(max_length=256)
questions = models.ManyToManyField(Questions, through='Questionnaire')
class Questionnaire(models.Model):
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
question_order = models.IntegerField()
The details and example can be found here:
https://docs.djangoproject.com/en/3.1/topics/db/models/#extra-fields-on-many-to-many-relationships. If you do not want to mess up with the models, then you have to find out some hack like was proposed by Ronak Muhta.
Small dilemma here; I want to allow users to create a list of tasks (via a model form) which will be stored in the database for them to read or update each of the fields in future (so to mark a task as completed for example).
In the model I've created something like this...
tasks_to_do = models.CharField(max_length=300, null=True)
However, I want users to be able to add as many or as few different tasks as they want. Should I do something like...
task_1 = models.CharField(max_length=100, null=True)
task_2 = models.CharField(max_length=100, null=True)
task_3 = models.CharField(max_length=100, null=True)
etc., which seems quite tedious/wasteful of code.
Or should I somehow try to store a series of strings as a list?
Apologies for the lack of code; very unsure about how to approach this problem as I haven't come across anything like this before.
Thanks in advance!
I think the easiest and the most obvious solution would be to to create two separate models - one for tasks list and another for a single task.
class TodoList(models.Model):
# you can put here some additional information, like the name of the list, when it was created etc.
class Task(models.Model):
todo_list = models.ForeignKey(TodoList)
# you can put extra info about the single task (the creator, date due etc.)
So everytime you want to add a new task to your list, you create another Task object with todo_list field's value set to TodoList object.
Or you can add it another way, using reverse relationship as described in docs
I have a silly Job model in my app:
class Job(models.Model):
# working info
user = models.ForeignKey(User)
company = models.CharField(max_length=100, blank=True)
department = models.CharField(max_length=100, blank=True)
inaugural_date = models.DateField('inaugural date', blank=True)
resignation_date = models.DateField('resignation date', blank=True)
the above model is exactly what I have in my app and this model is used to let user get their college, nothing more.
It works, but I think there must be a better way to design this model, because suppose I want get all the users within the same company and same department in same period of time, its not that easy.
Please help me to reconstruct this model, any suggestion will be appreciated!
This should work:
User.objects.filter(
job_set__company__iexact="wwwww",
job_set__department__iexact="xxxxx",
job_set__inaugural_date__gt=yyyy,
job_set__resignation_date__lt=zzzz
)
It doesn't seem that complex to me, such query wouldn't be easy if you think in SQL terms, at least for me :)
Depends how much you predict on growing and what backend you use. For relation db (mysql/postgres etc) I would create a separate model for departments and companies and also create join tables for them in order to make my job easier later on.
Your model looks fine.
Even though Django model is not Anemic , I usually look it as pure data structure without too much logic. So I think
get all the users within the same company and same department in same period of time
is a logic which should not be a concern of your model, which also means, it should not influence your model design too much IMHO.
Model should be kept simple and thin, so that it can be adopted and adapted in/to different kinds of logic. If you try to make you model structure suitable to a specific logic, you will easily find yourself entangled with inflating models.
BTW, for complex query, you can fallback to Raw SQL