So I am able to generate a random id using uuid
So far so good
But when I try to database i get same value
def f():
d = uuid4()
str = d.hex
return str[0:16]
class Q(models.Model):
a = models.CharField(max_length=150)
b = models.IntegerField(max_length=25)
c = models.IntegerField(max_length=32 , default=0)
d = models.ManyToManyField(Ans , related_name='aa')
e = models.CharField(max_length=18 , default = f() ,unique=True )
class Ans(models.Model):
sub = models.CharField(max_length=150)
-----------------------------------------------------------------
And I'm inserting like this
def ins(request):
t =random.randint(0, 1000)
p = Q(a = t , b=0 , c=0)
p.save()
return HttpResponse('Saved')
Just curious what the hell is happening here
Side note: If I set e.unique = False I get 2-3 with the same e values before I get a new
UUID values
You should not call the function that you are passing to default:
e = models.CharField(max_length=18, default=f, unique=True)
FYI, according to docs, you should pass a value or a callable:
The default value for the field. This can be a value or a callable
object. If callable it will be called every time a new object is
created.
Related
I have a factory boy factory that uses Django that I need to access the ID of the generated objects. However, whenever I attempt to get that ID, I receive TypeErrors. Any idea what I am missing?
# factories.py
class PartNoFactory(factory.django.DjangoModelFactory):
class Meta:
model = PartNo
id = factory.fuzzy.FuzzyInteger(1, 1000000, step=1)
# have also tried id = factory.Sequence(lambda n: n + 1)
# have also tried id = int(factory.Sequence(lambda n: n + 1)), which results in error "type Sequence cannot be assigned to paramater "_x"
# test_factories.py
def mock_child_part_nos(arg_1: PartNo) -> 'list[int]':
mock_part_no_one = PartNoFactory()
mock_part_no_two = PartNoFactory()
mock_part_no_three = PartNoFactory()
return [mock_part_no_one.id, mock_part_no_two.id, mock_part_no_three.id]
# if using FuzzyInteger: "Expression of type "list[FuzzyInteger]" cannot be assigned to return type "list[int]"
# if using Sequence: "Expression of type "list[Sequence]" cannot be assigned to return type "list[int]"
I am trying to count the sales made by a worker but I get the following error when using the code mentioned below:
TypeError: object of type 'bool' has no len()
class Movement_type (models.Model):
_name = 'project_rc.movement_type'
_rec_name = 'movement_type'
type_movement = fields.Selection ([('purchase', 'Purchase'), ('sale', 'Sale'), ('merma', 'Merma')], string = "Movement type", required = True)
class Worker (models.Model):
_name = 'project_rc.worker'
_rec_name = 'name'
sales_counter = fields.Integer (string = "Sales made", compute = "get_sales_realized", store = True)
#api.depends('move_type_ids')
def get_sales_realized (self):
for rec in self:
rec.count_sale = len (rec.move_type_ids.mov_type == 'sale')
I'm not familiar with whatever framework you are using, but if you look at the error you are getting you can see that it is correct.
On line 3, you write rec.move_type_ids.mov_type == 'sale'. It doesn't matter what rec.move_type_ids.mov_type is, when you compare it to something with ==, the answer will either be True or False. It doesn't make sense to take the length of a boolean (t/f).
From the context, I'm guessing that rec.move_type_ids is a list of objects and you want to figure out how many of them have a mov_type property equal to 'sale'. If that's the case, then you could easily do that with a for loop:
sales = []
for thing in rec.move_type_ids:
if thing.type == 'sale':
sales.append(thing)
rec.count_sale = len(sales)
If you want to get a little fancier, you can do that with a filter function:
rec.count_sale = len(filter(lambda x: x.mov_type == 'sale', rec.move_type_ids))
I am trying to calculate a value from GraphQL. I am sending mutation to Django models but before save it I want to calculate this value with if statement (if the value is greater than 10 divide by 2, if is less than 10 multiply by 2).
I don't know where to add this function.
Here is my mutation in schema.py
class CreatePrice(graphene.Mutation):
price = graphene.Field(PriceType)
class Arguments:
price_data = PriceInput(required=True)
#staticmethod
def mutate(root, info, price_data):
price = Price.objects.create(**price_data)
return CreatePrice(price=price)
class Mutation(graphene.ObjectType):
create_product = CreateProduct.Field()
create_price = CreatePrice.Field()
schema = graphene.Schema(query = Query, mutation=Mutation)
And here is my Django model. Base price is calculated value and function name has two options(*2 or /2 it depends of initial value).
class Price(models.Model):
base_price = models.CharField(max_length = 20)
function_name = models.CharField(max_length = 20, choices = PROMO_FUNCTION)
def __str__(self):
return self.price_name
P.S. Sorry for bad English. Thanks!
I don't know why you are using CharField for base_price. So, I suggest you to do this:
#staticmethod
def mutate(root, info, price_data):
if int(price_data.base_price) >= 10:
price_data.base_price = str(int(price_data.base_price) / 2)
else:
price_data.base_price = str(int(price_data.base_price) * 2)
price = Price(base_price=price_data.base_price, function_name=price_data.function_name)
price.save()
return CreatePrice(price=price)
You can also create records in database by creating object and using save method on it.
I have a model like this:
class meter1(models.Model):
U1N = models.FloatField(default=0)
U2N = models.FloatField(default=0)
In my view (simplified) I want to set the value for the database dynamically:
def import_data:
dict = {"1":"U1N","2":"U2N",}
c = "1"
q = meter1()
q.eval('dict[c]') = "1"
q.save()
In real dict contains 60 items, and c changes every time in a for loop. The code in this example results in an error: NameError: name 'U1N' is not defined.
How do I dynamically set the keyword for q?
You can also dynamically build a dict from your dict (you shouldn't use a builtin name as identifier BTW) and pass it as kwargs to meter1() (you shouldn't use all-lowers as class names BTW). Oh and yes: you may want to have a look at modelmanager.create() too.
def import_data():
fieldmap = {"1":"U1N","2":"U2N",}
fieldindex = "1"
kw = {fieldmap[fieldindex]: 1.0}
# either:
q = Meter1(**kw)
q.save()
# or:
q = Meter1.objects.create(**kw)
You can use setattr to dynamically set attributes to the objects.
I have the following classes defined that inherits from some other classes. Goblin is a Python dependency package that I am extending from.
class AnnotatedVertexProperty(goblin.VertexProperty):
notes = goblin.Property(goblin.String)
datetime = goblin.Property(DateTime)
class KeyProperty(goblin.Property):
def __init__(self, data_type, *, db_name=None, default=None, db_name_factory=None):
super().__init__(data_type, default=None, db_name=None, db_name_factory=None)
class TypedVertex(goblin.Vertex):
def __init__(self):
self.vertex_type = self.__class__.__name__.lower()
super().__init__()
class TypedEdge(goblin.Edge):
def __init__(self):
self.edge_type = self.__class__.__name__.lower()
super().__init__()
class Airport(TypedVertex):
#label
type = goblin.Property(goblin.String)
airport_code = KeyProperty(goblin.String)
airport_city = KeyProperty(goblin.String)
airport_name = goblin.Property(goblin.String)
airport_region = goblin.Property(goblin.String)
airport_runways = goblin.Property(goblin.Integer)
airport_longest_runway = goblin.Property(goblin.Integer)
airport_elev = goblin.Property(goblin.Integer)
airport_country = goblin.Property(goblin.String)
airport_lat = goblin.Property(goblin.Float)
airport_long = goblin.Property(goblin.Float)
At run time, I need to iterate thrown each one of the properties and be able to determine its class type (keyProperty or goblin.Property) I also need to be able to determine if the value is a string, integer, etc...
During instantiation, I create an airport object and set the values as following:
lhr = Airport()
lhr.airport_code = 'LHR'
print (lhr.airport_code.__class__.mro())
lhr.airport_city = 'London'
lhr.airport_name = 'London Heathrow International Airport'
lhr.airport_region = 'UK-EN'
lhr.airport_runways = 3
lhr.airport_longest_runway = 12395
lhr.airport_elev = 1026
lhr.airport_country = 'UK'
lhr.airport_lat = 33.6366996765137
lhr.airport_long = -84.4281005859375
However when I inspect the object while debugging it, all I get is the property name, defined as string and values, defined as string, integer, etc... How can I check for the object type for each property?
Any help or suggestions on how to handle this ?
I figured out what I was looking for. I had to call element.class.dict.items(): and I can get a dictionary with all the properties, mappings, etc...