Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

django - How to create a model with a field that contains the unique values from a field in another model?

Using django 3.1.3

I have a model (Item) that holds all items submitted by users. All of these items are grouped into user-defined categories. Each record contains the item name and the category name.

What I want to do is create a second model (Category) that will have two fields:

  • category: populated with the unique values from the category field in (Item
  • include: A boolean that indicates if 'category' should be included

So lets say that model (Item) has the following unique categories: 'Clothes', 'Groceries', 'Chairs'. I want (Category) > category to contain one record for each of those unique values. How can I structure model (Category) to accomplish this?

Here's the relevant portion of model (Item):

class Item(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    include = models.BooleanField(default=False)
    quantity = models.PositiveIntegerField(default=0)
    category = models.CharField(max_length=20)
    item = models.CharField(max_length=50) 

And here's what I have for (Category):

class Category(models.Model):
    include = models.BooleanField(default=True)
    category = ????
question from:https://stackoverflow.com/questions/65910023/how-to-create-a-model-with-a-field-that-contains-the-unique-values-from-a-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This sounds like a prime example of using a ManyToMany field on your Item model. Basically what Django will do is create what is called a Through model that will allow you to relate multiple Categories to multiple Items. Here is the documentation for further reference:

https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...