How to create multiple entries of same field? - django-models

model.py:
class Model1(models.Model):
#4 fields of type CharFieldvalues excepted from a user.
class Model2(models.Model):
field1 = models.OneToOneField(Model1, on_delete=models.CASCADE)
How can I create multiple entries of field1. The number of field1 could be 1 or 2 or more for each Model2 instance.

Related

How to use particular field of a model into another model, like I want to use sku as a foreign key in next model?

class Product(models.Model):
price=models.IntegerField()
no=models.IntegerField(default=0,null=True)
sku= models.CharField(max_length=100,default=0,null=True )
#Here I want to use sku into another model as a foreign key
In that case, the sku needs to be unique, and non-nullable, since otherwise it can not refer to a product properly, so:
class Product(models.Model):
price = models.IntegerField()
no = models.IntegerField(default=0, null=True)
sku = models.CharField(max_length=100, unique=True)
Then you can work with the to_field=… parameter [Django-doc]:
class Order(models.Model):
product = models.ForeignKey(Product, to_field='sku', on_delete=models.CASCADE)
Then if you use my_order.product_id, it will contain the sku of the product it refers to.

Django queryset for DRF view

I have model called Category where we can add the categories and the records will be a manytomanyfield to Records Model what can my queries be to display all the categories on one page and the if i click on the particular category i should get only records related to that particular category.
models.py
class Category(models.Model):
name = models.CharField(max_length=255, blank=True)
records = models.ManytoManyField(Record)
class Record(models.Model):
name = models.CharField(max_length=255, blank=True)
views.py
class CategoryListView(ListAPIView):
def get_queryset(self):
queryset = ?
return queryset
class RecordListView(ListAPIView):
def get_queryset(self):
queryset = ?
return queryset
/categories/page/
Category 1
Category 2
Category 3
Category 4
/Category/Records/page/
Category 1
record 1
record 2
record 3

Django multiple queryset and concatenation

I am building an advance search in django/angular where user can select one or more fields from different models
############# ############# #############
Model1 Model2 Model2
############# ############# #############
Field1 Field1 Field1
Field2 Field2 Field2
Field3 Field3 Field3
...... Fk(Model1) Fk(Model1)
....... ..........
Model2, Model3 and other models have foreignkey reference to Model1.
The selected models fields are send to the django views for further queries and result concatenation.
views.py
def customsearch(request):
queryrequest = json.loads(request.body)
result = []
print queryrequest
""" [{u'value': u'Field1', u'key': u'Model1'}, {u'value': u'Field2', u'key': u'Model2'}, {u'value': u'Field3', u'key': u'Model2'}, {u'value': u'Field2', u'key': u'Field2'}]"""
for item in queryrequest:
if(item['key'] == 'Model1'):
result.append(Model1.objects.filter().values(item['value']))
else:
result.append(item['key'].objects.filter().values(item['value']).select_related('fk'))
I have got a request of list of dictionaries. The list consist of key (model name) and value (field).
How can i make a queries and contenate results based on above example?
I am newbie to django!
Any helps and suggestions are welcome.
if your model2, model3 has fk to model1,
this is sample (you should use related_name for Model2, Model3 ForeignKey Field)
from django.db.models import Q
Model1.objects.filter(
Q(Field1=value1) &
Q(model2_related_name__Field2=value2) &
Q(model3_related_name__Field3=value3)
)
and, about related_name this

Backbone: adding models to a collection

On the one hand, i have three CollectionsView (three types of models fetched from the server), on the other hand i have a quarter CollectionView that works like a shopping cart. This stores items from the other three Collections associated with the views (Collections Views).
The problem is when i add a item with the same id this is edited, not added to the Shopping cart CollectionView.
Example:
function addToCart(model){
ShoppingCartCollectionView.collection.add(model);
}
From the others collections:
// From one CollectionView
addToCart(this.model);
// From another CollectionView
addToCart(this.model);
This Collections have the same id because they are stored in diferent databases on the server.
This is my model (Python ORM)
PRODUCT_TYPE = (
('EM', 'Empanada'),
('BE', 'Bebida'),
('OF', 'Oferta'),
)
# Create your models here.
class Producto(models.Model):
nombre = models.CharField(max_length=50)
precio_unidad = models.DecimalField(max_digits=8, decimal_places=2)
descripcion = models.TextField()
stock = models.IntegerField()
status = models.BooleanField(default=True)
imagen = models.ImageField(upload_to=upload_to)
fecha_publicacion = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class Empanada(Producto):
precio_docena = models.DecimalField(max_digits=8, decimal_places=2)
product_type = models.CharField(max_length=2, choices=PRODUCT_TYPE, default='EM', editable=False)
def __unicode__(self):
return self.nombre
class Bebida(Producto):
product_type = models.CharField(max_length=2, choices=PRODUCT_TYPE, default='BE', editable=False)
def __unicode__(self):
return self.nombre
class Oferta(Producto):
product_type = models.CharField(max_length=2, choices=PRODUCT_TYPE, default='OF', editable=False)
def __unicode__(self):
return self.nombre
class Venta(models.Model):
pedido = models.TextField()
total = models.DecimalField(max_digits=8, decimal_places=2)
status = models.BooleanField(default=True)
fecha_publicacion = models.DateTimeField(auto_now_add=True)
How to solve this?
THANKS !!!
#KimGysen is right about looking into restructuring your products tables. Having different products with the same id is going to cause you problems in the long run. Here's a database schema that may work for you.
Using foreign key tables
First you'd have a product name table where you'd list the name of your different products and assign each product type a primary key (ID). Then, group the different attributes of your product and make a separate table for each group. In the table you'd refer to your original product types by their ID (this is your foreign key). Here's a simple diagram:
/*Name Table Prod Type 1
------------------------------- ---------------------------------
| ID | Product Name | Prod Type | ProdId | attr1 | ... | attrN |
------------------------------- ---------------------------------
| 1 | Product 1 | 1 | | 1 | val1 | ... | valN |
------------------------------- ---------------------------------*/
Work with or around collection.set
Your other option is to override the collection.set method in Backbone, which is responsible for identifying whether there are duplicates in your set.
Cheating collection.set
If you're having problems because your adding two different types of products with the same id you can cheat collection.set by making sure that their id attribute is called something other than id (this is what set uses to evaluate whether you have to identical models in your collection, unless you tell it to check a different property by setting the idAttribute property in your model definition). Then collection.set will not know how to match incoming models.
Overriding collection.set
If you're having trouble because collection.set is not storing a model that is already in your collection, then you will have to override collection.set. Let me know if this is the fix you're looking for and I'll post that answer here.
Create a new ShoppingCart Model
A third possibility is to have a ShoppingCart model that handles the addition and removal of models. This is a more complicated solution. If you provide more details about how your cart is being used I can drop a few ideas on how to get your started.

How to design a table which have many-to-many relationship with itself?

For example, A Users entity has a friends property, how can I design this friends property, in my thought there are 2 ways:
friends property is a String with all usernames splitted by "," in this way it's hard to read and modify.
friends property is a Set like Set<Users>, but in this way I don't know how to write in entities?
Anyone knows the best practise?
This is covered Enterprise Model Patterns by Hay.
A party represents a person (or an organization):
Party
id
name
A party can have a relationship to another party, over a time period:
PartyRelationship
fromPartyId
toPartyId
fromDate
toDate nullable
A basic diagram:
Party -< PartyRelationship >- Party
Sample SQL:
insert into party values (1, 'Jerry');
insert into party values (2, 'Neil');
insert into partyRelationship values (1, 2, getDate(), null);
If a User can have multiple friends you could annotate your User entity like this:
#Entity
public class User
{
#Id
private Long id;
private String name;
#ManyToMany
#JoinTable(
name = "user_friends",
joinColumns =
{ #JoinColumn(
name = "user_id") },
inverseJoinColumns =
{ #JoinColumn(
name = "friend_id") })
private Set<User> friends;
}
This way a table will get created for User and a join table for the relationship between Users. The User table will have 2 columns, 'id' and 'name'. The user_friend table will have 2 columns, 'user_id' and 'friend_id'. The columns in user_friend are both foreign keys to the User table.

Resources